Skip to content Skip to sidebar Skip to footer

Trying To Get A Canvas To Follow Another Canvas, It Goes Crazy

Okay. I'm having two canvases. First canvas (rect1) is going to be moving randomly on the gameboard. The second (zombie) is supposed to follow rect1, but it just runs all over the

Solution 1:

These statements:

if (zombie.x > rect1.x){
  zombie.velX *= -1;
}
if (zombie.y > rect1.y){
  zombie.velY *= -1;
}

don't work as intended. They flip velocities only if the zombie position is smaller than the rectangle. Instead you want to flip velocities if the velocity is going in the wrong direction.

So instead it should be something like:

if (Math.sign(rect1.x-zombie.x)!==Math.sign(zombie.velX)){
  zombie.velX *= -1;
}
if (Math.sign(rect1.y-zombie.y)!==Math.sign(zombie.velY)){
  zombie.velY *= -1;
}

updated fiddle: https://jsfiddle.net/easvqk6m/6/

Solution 2:

The problem is that you're always flipping the velocity. Imagine this:

// Init
zombie.velX = 3;
zombie.x = 300;
rect1.velX = 3;
rect1.x = 100; // rect1 is to the left of zombie// Frame 1if (zombie.x > rect1.x) { // 300 > 100
  zombie.velX *= -1; // zombie.velX === -3
}
zombie.x += velX; // zombie.x === 297// Frame 2if (zombie.x > rect1.x) { // 297 > 100
  zombie.velX *= -1; // zombie.velX === +3
}
zombie.x += velX; // zombie.x === 300

And this kind of cycle repeats forever. Instead, you can use the absolute value of it's velocity to specify which direction to go.

if (zombie.x > rect1.x) { // We want to move zombie to the left
  zombie.velX = -Math.abs(zombie.velX);
} else { // We want to move zombie to the right
  zombie.velX = Math.abs(zombie.velX);
}

Post a Comment for "Trying To Get A Canvas To Follow Another Canvas, It Goes Crazy"