Canvas 游戏移动精灵

Canvas game move sprite

我正在创建一个小游戏,我试图让我的 Enemy 精灵从 canvas 墙上随机反弹(当它撞到 [=19 的墙壁/边缘时改变方向并随机飞走) =]) 示例 - [http://www.onlywebpro.com/2011/07/20/html5-canvas-for-absolute-beginners-part-4/]

这是我的移动敌人的功能,但不幸的是它不起作用,敌人飞出了canvas的边缘,有人可以帮忙吗?

Enemy.prototype.update = function () {

    this.drawX = this.drawX +5 ;
    this.drawY = this.drawY+ 5;

if ((this.x + 2) >= canvasWidth || (this.x - 2) <= 0) 
{    
this.x = -2;   
}

  if ((this.y + 2) >= canvasHeight || (this.y - 2) <= 0) { 
        this.y = -2;
      }
     } 

非常感谢,

当你想让物体改变方向时,不仅仅需要改变位置,还需要改变它当前的运动向量。当前,您的运动矢量在第 3 行和第 4 行中被硬编码为 +5+ 5

将你的运动矢量移动到你在对象的构造函数中设置的变量:

this.moveX = 5;
this.moveY = 5;

然后通过该变量而不是硬编码值更改每帧的位置:

this.x = this.x + this.moveX ;
this.y = this.y + this.moveY ;

当您检测到水平或垂直碰撞时,反转相应的运动矢量:

if ((this.x + 2) >= canvasWidth || (this.x - 2) <= 0) 
{    
    this.moveX = -this.moveX;   
}

if ((this.y + 2) >= canvasHeight || (this.y - 2) <= 0) { 
    this.moveY = -this.moveY;
}