I want to make a program which sets ellipses next to each other until one touches a border of my canvas and then proceeds in the other direction. Unfortunately it only works in one direction and stops when it hits the right border.Is there a way to save the sx
variable at some point to use it again in the second if statement?
void setup() {
size(700, 500);
frameRate(20); // frame rate = 20 Hz
}
int sx=50;
int sy=50;
int dx=15;
void draw() {
if(sx<width){
ellipse(sx,sy,20,20);
sx=sx+dx;
if(sx>width){
sx=sx-dx;
}
}
}
sx
is in global scope, so there is no need to "store" it, because the value is persistent.
What you want to do is quite simple. The key is dx
rather than sx
. If the the ellipse reaches the border of the window, the direction has to be changed. This can be achieved by inverting dx
.
Invert dx
( dx *= -1
) when sx
is at the right border ( sx >= width
) or left border ( sx <= 0
). eg:
void setup() {
size(700, 500);
frameRate(20); // frame rate = 20 Hz
}
int sx=50;
int sy=50;
int dx=15;
void draw() {
background(196);
ellipse(sx,sy,20,20);
sx=sx+dx;
if (sx >= width || sx <= 0 ){
dx *= -1;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.