question about color in my code
in
Programming Questions
•
1 year ago
Basically we were given a template and had to fill in some blanks to create the balls and then make them move and collide.
The last problem I am having is I need the balls colors to be randomised each run of the program from and RBG scale.
This is simple enough to do by making 3 floats and making them random (0, 255), but this isnt how they want us to do it, they want us to use color.
Thanks for any help in advance :)
Here is the code so far
- class Ball {
- float rad; // radius
- float x,y; // center's position of the ball
- float speedX; // for horizontal speed
- float speedY; // for vertical speed
- color c; // color of the ball
- // constructor for initialization
- Ball() {
- rad = random (20, 40);
- x = random (0+rad, width-rad);
- y = random (0+rad, height-rad);
- speedX = random (-5, 5);
- speedY = random (-5, 5);
- c = random (0,255);
- // write some code
- }
- // display a ball with the given x, y and rad, filled with c
- void display() {
- fill(c);
- noStroke();
- ellipse(x, y, rad*2, rad*2);
- }
- // set the new position according to speedx and speedy
- // and check if a bounce happens
- void moveBall() {
- x += speedX;
- y += speedY;
- if (x > width-rad || x < 0+rad)
- speedX *= -1;
- if ( y > height-rad || y < 0+rad)
- speedY *= -1;
- }
- // dispaly a ball and let it move
- void play() {
- display();
- moveBall();
- }
- // check if collision happens
- // returns true two balls collide; otherwise returns false
- boolean collideWith(Ball other) {
- float gap = dist(x, y, other.x, other.y);
- if (gap <= rad + other.rad)
- return true;
- else
- return false;
- }
- }
- // don't change anything below
- Ball b1, b2;
- void setup() {
- size(400, 400);
- b1 = new Ball();
- b2 = new Ball();
- smooth();
- }
- void draw() {
- background(255);
- if (b1.collideWith(b2)) {
- b1.display();
- b2.display();
- }
- else {
- b1.play();
- b2.play();
- }
- }
1