Moving circle with arrow keys

hello everyone,
I have an assignment that says i have to make a circle that moves when the arrow keys are pressed and it shouldn’t leave the canvas, but i’m having a problem with keeping the circle within the canvas…i need help

here is what i have so far.

float x;
float y;
int rad;

 
void setup(){
  size (200, 200);
  x = width/2;
  y = height/2;
}
 
void draw(){
  background(0,255,0);
  fill(255,0,255);
  ellipse(x, y, 50,50);
}
 
void keyPressed() {
  if ((keyPressed == true) && (key == CODED)) {
    if (keyCode == UP){
     y --;
    } else if (keyCode == DOWN && y-rad <= 175) {
      y ++;
    } else if (keyCode == LEFT && x-rad >= 27){
      x --;
    } else if (keyCode == RIGHT) {
      x ++;
    }  
  } 
}

hi,
somehow the concept with the radius is not functional.
try:

float x;
float y;
int rad = 25;

void setup() {
  size (200, 200);
  x = width/2;
  y = height/2;
}

void draw() {
  background(0, 255, 0);
  fill(255, 0, 255);
  ellipse(x, y, 2*rad, 2*rad);
}

void keyPressed() {
    if      (keyCode == UP    && y-rad >= 0     )  y --;
    else if (keyCode == DOWN  && y+rad <= height)  y ++;
    else if (keyCode == LEFT  && x-rad >= 0     )  x --;
    else if (keyCode == RIGHT && x+rad <= width )  x ++;
}

you notice how good my code is formatted

  • in the IDE by [ctrl][t]
  • here at the forum editor with using the
</> code tag
1 Like

Thank you for your help.

1 Like

I think your main error was just that rad was 0 ! You forgot to give it a value

Also you don’t use rad in ellipse() command

Also you can give x and y initial values

2 Likes

Using this code, is there a way to increase the speed of the object moving, and make it smoother?

Thanks!

Well, the location of the object is defined by x and y. Changing the values of x and y are how it moves – how fast it moves is controlled by how much you change x and y – by 1, by 5, by 10 etc.

Can you currently see where x and y are changed in the code, so that you could adjust the speed?

1 Like

Studio.ProcessingTogether.com/sp/pad/export/ro.91tcpPtI9LrXp