Parameters in classes

So my code is below. The assignment was to make 3 bouncing balls, the intent was to do it with one class and float x,y,size, and color. I tried our book, online tutorials, and trial and error. But every time I used a parameter, the ball(s) wouldn't move. I had to relent and use 3 different classes. Could anyone explain how to do it with just 1+parameters? (I only included the code for one class to keep it simple, but you get the idea). Thanks in advance.

Ball b;
Ball2 b2;
Ball3 b3;
void setup(){
  size(600,700);
  background(255);
  b= new Ball();
  b2= new Ball2();
  b3= new Ball3();
}//end setup

void draw(){
  background(255);
  b.ball();
  b.bounce();
  b2.ball2();
  b2.bounce();
  b3.ball3();
  b3.bounce();
}//end draw

class Ball{
  float x=50;
  float y=0;
  float gravity=0.1;
  float speed=0;
  void ball(){
    fill (0,0,255);
    ellipse(x,y,50,50);
  }//end constructor
  void bounce(){
    y=y+speed;
    speed=speed+gravity;
    if (y>height){
    speed=speed*(-0.95);
    y=height;
   }//end if  
  }//end bounce
}//end class
Tagged:

Answers

  • edited November 2016

    Code did not display as expected, here is a screen shot

    Edit:screenshot deleted

  • edited November 2016

    No screenshots please -- nobody can test that. Edit with gear icon, replace with pasted code, highlight and format code with CNTRL+o.

    https://forum.processing.org/two/discussion/15473/readme-how-to-format-code-and-text#latest

  • Your constructor should be Ball(), not ball().

    You draw the ball in the class's constructor function, and this happens once. Perhaps you should add a draw() function to your class - one that draws the ball - instead.

  • edited November 2016

    Thanks for the displaying code tip.

    TfGuy44, I think the way it is written there is no constructor correct? But that aside, I also used the constructor method "Ball()" and that would work, but not with parameters, for whatever reason, whenever I added parameters the balls would cease to move, although the balls would still be drawn.

    This code I posted works, but I'm trying to condense it into one class. (I omitted Ball2 and Ball3 for brevity).

    I would like to be able to write say

    b.ball(x,y,color,size);
    

    in draw, and then just specify x,y,color,and size, for different ones, but using the same class.

  • So far no, everything I've tried results in drawing the ball(s) but with no movement.

  • Finally figured it out with some help from the professor, I thought that the b.x or b1.x required different classes, and that the parameters were defined in the void, rather than in the designators before setup. My (flawed) logic was "ok now we are drawing in void draw, this is where I'll tell it where to put stuff." Thanks for the help.

Sign In or Register to comment.