Javascript 帆布游戏移动精灵

Javascript 帆布游戏移动精灵,javascript,canvas,html5-canvas,Javascript,Canvas,Html5 Canvas,我正在创建一个小游戏,我试图让我的敌人精灵从画布墙壁上随机反弹(改变方向,当它击中画布的墙壁/边缘时随机飞离) 示例-[ 这是我的移动敌人的功能,但不幸的是它不起作用,敌人飞离画布的边缘,有人能帮忙吗 Enemy.prototype.update = function () { this.drawX = this.drawX +5 ; this.drawY = this.drawY+ 5; if ((this.x + 2) >= canvasWidth || (this

我正在创建一个小游戏,我试图让我的敌人精灵从画布墙壁上随机反弹(改变方向,当它击中画布的墙壁/边缘时随机飞离) 示例-[

这是我的移动敌人的功能,但不幸的是它不起作用,敌人飞离画布的边缘,有人能帮忙吗

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;
      }
     } 
敌方.prototype.update=函数(){
this.drawX=this.drawX+5;
this.drawY=this.drawY+5;

如果((this.x+2)>=canvasWidth | | |(this.x-2)=canvasHeight | | |(this.y-2)当您希望对象更改方向时,您不仅需要更改位置,还需要更改其当前运动向量。当前,在第3行和第4行中,您的运动向量被硬编码为
+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;
}
if((this.x+2)>=画布宽度| | |(this.x-2)=画布高度| | |(this.y-2)