试图让画布跟随另一个画布,它变得疯狂 [英] Trying to get a canvas to follow another canvas, it goes crazy

查看:167
本文介绍了试图让画布跟随另一个画布,它变得疯狂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好。我有两幅画布。第一个画布(rect1)将在游戏板上随机移动
。第二个(僵尸)应该跟随rect1,但它只是遍布整个地方。这是我认为应该足以发现错误的最重要的代码。

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;

这是一个小提琴 https://jsfiddle.net/Scrubben/easvqk6m/1/ ,你可以看到僵尸(红色)的行为。很抱歉有两个rects并且没有在jsfiddle中评论,但你应该明白这个想法。如果您希望我澄清或添加更多代码,请告诉我!谢谢

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

推荐答案

这些陈述:

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.

所以它应该是这样的:

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;
}

更新小提琴: https://jsfiddle.net/easvqk6m/6/

这篇关于试图让画布跟随另一个画布,它变得疯狂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆