Trying to get a canvas to follow another canvas, it goes crazy

烂漫一生 提交于 2019-12-25 04:42:48

问题


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 place. Here is the most important code which I think should be enough to spot out what is wrong.

var rect1={
  x:300,
  y:150,
  width:8,
  velX:3,
  velY:3
};
var zombie={
  x: 100,
  y: 100,
  width: 10,
  velX: 3,
  velY: 3
};

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

    zombie.x+= zombie.velX;
    zombie.y+= zombie.velY;

Here's a fiddle https://jsfiddle.net/Scrubben/easvqk6m/1/ where you can see how the zombie (in red) behaves. Sorry for having two rects and for not commenting in the jsfiddle very well but you should get the idea. If you want me to clarify or add me any more code please let me know! Thanks


回答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/




回答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 1
if (zombie.x > rect1.x) { // 300 > 100
  zombie.velX *= -1; // zombie.velX === -3
}
zombie.x += velX; // zombie.x === 297

// Frame 2
if (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);
}


来源:https://stackoverflow.com/questions/37036399/trying-to-get-a-canvas-to-follow-another-canvas-it-goes-crazy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!