Reputation: 95
I am attempting to add collision detection with the edges using 4 images which represent a walking man. Once the image hits the wall it should reverse and move the other way until it hits the wall and reverses direction once again. How would i go about this? Here is my code so far:
class Walker {
int x = 0;
int y;
int speed;
PImage img1, img2, img3, img4;
int count = 0;
Walker(int y, int speed) {
this.y = y;
img1 = loadImage("walk1.gif");
img2 = loadImage("walk2.gif");
img3 = loadImage("walk3.gif");
img4 = loadImage("walk4.gif");
this.speed = speed;
}
void render() {
if (count < 10)
image(img1, x, y);
else if (count < 20)
image(img2, x, y);
else if (count < 30)
image(img3, x, y);
else if (count < 40)
image(img4, x, y);
else {
count = -1;
}
count++;
}
void move() {
x = x + speed;
}
}
Walker walter;
void setup() {
size(500, 500);
walter = new Walker(150, 3);
}
void draw() {
background(125);
walter.render();
walter.move();
}
Upvotes: 0
Views: 178
Reputation: 210968
You have to reverse the speed, when ever the walker hits the wall. The width of an PImage
is given by the property .width
e.g.:
class Walker {
// [...]
void move()
{
x = x + speed;
int man_width = img1.width;
if (x <= 0 || x >= width-man_width)
speed = -speed;
}
}
Upvotes: 1