Loading...
Logo
Processing Forum
int x;
int xspeed;
int y;
int yspeed;

void setup(){
  size(500,500);
  x=25;
  
  y=250;
  
}
void draw() {
  
  int r=random (-2,2);
  yspeed=r;
  xspeed=r;
  if(x > width-25){
    xspeed = xspeed*(-1);
  }
  if(x < width-475){
    xspeed = xspeed *(-1);
  }
  if(y > height-25){
    yspeed = yspeed *(-1);
  }
  if(y <height-475){
    yspeed = yspeed *(-1);
  }
  x = x+xspeed;
  y = y+yspeed;
  background(255);
  fill(#AA7DFE);
  stroke(#0EE31A);
  ellipse(x,y, 50,50);
}

Replies(8)

When you set xspeed to r and yspeed to r, you set them to the same thing.
Your variable r remembers the single random number it was assigned.
It does not remember that it called a function!

You probably want to do this instead:

xspeed = random(-2,2);
yspeed = random(-2,2);

And you probably want to do that inside setup()!
I did that and now there is an error message saying "cannot convert from float to int".

Your speeds should probably be floats, not ints.
Change int x; and int y; to float x; and float y;
now the ball does not bounce around any more. How can I keep the ball bouncing around inside the screen and still have  random speed.
 if(x > width-25){
    xspeed = xspeed*(-1);
    x = width-25;
  }
  if(x < width-475){
    xspeed = xspeed *(-1);
    x = width-425;
  }
  if(y > height-25){
    yspeed = yspeed *(-1);
    y=height-25;
  }
  if(y <height-475){
    yspeed = yspeed *(-1);
    y=height-475;
  }