We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Class Syntax & Constructors
Page Index Toggle Pages: 1
Class Syntax & Constructors (Read 278 times)
Class Syntax & Constructors
Oct 11th, 2008, 12:57am
 
Hi,

I'm starting to learn about classes, and I'm having some frustration with some of the basic elements of class syntax. I've started with a simple line drawing. It runs as follows:

Quote:
float x = 1.0;
float speed = .05;

void setup() {
  size (900,900);
  smooth ();
  loop();
 
}

void draw () {
  background (255);
  translate (width/2,height/2);
  for (int i =0; i <20; i++) {
    rotate (PI/7);
    strokeWeight (i);
    line (0,0,x+55,0);
    x= x+speed;
}
}
 


I'm trying to format this code as a class so it can be further manipulated copied, etc. However, I seem to not really understand how a constructor works, despite my efforts. What am I doing wrong in the following code, so that I'm not getting the same results as above?

Quote:
Firework fw;

void setup() {
  size (900,900);
  smooth ();
  loop();
  fw = new Firework (0,0,0,0);
}


void draw () {
  background (255);
  fw.display();
  }

class Firework {
  float x,y;

  
Firework(float xpos,float ypos, float xpos, float ypos) {
    x = xpos;
    y = ypos;
  }
  
  
    
  void display () {
    translate (width/2,height/2);
    for (int i =0; i <20; i++) {
    rotate (PI/7);
    strokeWeight (i);
    line (x,y,x+55,y);
  }
}
}



Re: Class Syntax & Constructors
Reply #1 - Oct 11th, 2008, 8:59am
 
There is a syntax error, as you have twice the same parameters in the constructors.
Beside, in the class you don't have the speed factor. You should pass it in the constructor too, and use it to increment x as you did in the first version.

Code:
class Firework {
float x, y;
float speed;

Firework(float xpos,float ypos, float s) {
x = xpos;
y = ypos;
speed = s;
}

void display() {
translate(width/2, height/2);
for (int i = 0; i < 20; i++) {
  rotate(PI/7);
  strokeWeight(i);
  line(x, y, x+55, y);
  x += speed;
}
}
}
Page Index Toggle Pages: 1