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 ++;
}
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?