2014-06-06 15 views
0

当我在画布上绘制我的精灵图像,然后它假设反射出画布的两侧。但是当我在画布上绘制更多的精灵图像后,当我触碰到画布的一侧时,它会不停地反射,使其成为画布一侧的双重图像。下面是使其改变方向的代码:具有不停反射的雪碧图像

Fish.prototype.changeDirection = function() { 
    speedXSign = this.speedX > 0 ? 1 : -1; 
    speedYSign = this.speedY > 0 ? 1 : -1; 
    this.speedX = speedXSign * (1 + Math.random() * 2); 
    this.speedY = speedYSign * (1 + Math.random() * 2); 
}; 

我的小提琴绘制多个精灵图像后检查出的错误:http://jsfiddle.net/Bernard_9/8gTNk/7/

回答

0

当鱼击中边,它应该反映。但是,您并没有检查鱼在碰到边的时候是否正朝移动。例如,鱼向右走,跑到右边的墙上。 speedX翻转,所以他以另一种方式行驶。下一次检查位置时,他仍然撞到墙上(即使他正在离开墙壁),所以speedX再次翻转(现在再次向右移动),所以他撞上墙壁,重复该过程。

固定码(注意检查speedX和快速):

if ((this.xPos + this.frameWidth * this.frameScale/2) >= canvas.width && this.speedX > 0 || 
    (this.xPos - this.frameWidth * this.frameScale/2) <= 0 && this.speedX <= 0) { 
    this.speedX = -this.speedX; 
} 

this.yPos += this.speedY; 
if ((this.yPos + this.frameHeight * this.frameScale/2) >= canvas.height && this.speedY > 0 || 
    (this.yPos - this.frameHeight * this.frameScale/2) <= 0 && this.speedY <= 0) { 
    this.speedY = -this.speedY; 
} 

http://jsfiddle.net/8gTNk/8/

+0

更新我从一个工作示例答案。请重新阅读我的解释。它拥抱墙壁,因为它在朝向和远离墙壁时与侧面“碰撞”。 – JustcallmeDrago

+0

此外,“复制”的鱼只是与每帧真正快的鱼翻转方向相同(左右,左右,左右,左右) – JustcallmeDrago