Hey guys,
I’m a very rookie at processing and something come up that I can not solve. I want to move a rect() pixel by pixel from left to right if the key ‘x’ is pressed.
My code looks like this so far:
color cl;
float x=200;
float y=200;
float x2=50;
float y2=50;
void setup(){
size(800,800);
cl = get(0,0);
}
void draw(){
rect(x,y,x2,y2);
}
void keyPressed() {
if (key == 'x') {
while(x2<100){
x2++;
x++;
}
}
}
So the main problem is as you can see that the rectangle is not moving but a new wide one is drawn.
What should be the solution.?
2 Likes
Hey Jack! I think I know what your problem is. Basically, what you’re doing with x2++
is increasing the size of the rectangle, rather than moving it by one pixel at a time. This is because when using rect(1, 2, 3, 4)
1 is the x position of the top left hand corner of the rectangle, 2 is the y position of the top left hand corner of the rectangle, 3 is the width of the rectangle and 4 is the height of the rectangle. So x2++
is increasing the size of the rectangle rather than moving it. So basically you just need to remove x2++
and keep x++
as that is the x position of the rectangle and thus increasing it by using ++
will increase it by one pixel every time the key ‘x’ is pressed.
Here is the code:
color cl;
float x=200;
float y=200;
float x2=50;
float y2=50;
void setup() {
size(800, 800);
cl = get(0, 0);
background(0);
}
void draw() {
rect(x, y, x2, y2);
}
void keyPressed() {
if (key == 'x') {
x++;
}
}
I also recommend using background()
so that the rectangle doesn’t leave a ‘trail’ when it moves.
Also, what is the purpose of your while loop? Is it just to make sure that the rectangle does not move off the screen?
3 Likes