2014-07-24 29 views
1

我的雪碧图像将在画布上随机移动。但是当我按下画布后,一个对象会出现,精灵图像将以曲折的方式朝它移动。但是我想让精灵直接移向物体。朝着一个特定点的雪碧运动风格

如何向像我的精灵形象的举动,我压在画布上之后创建的:

Fish.prototype.chaseFood = function(index) { 
    if (this.xPos > foodArray[index].x + foodWidth) { 
     this.speedX = -1 * Math.abs(this.speedX); 
    } else if (this.xPos < foodArray[index].x) { 
     this.speedX = Math.abs(this.speedX); 
    } 
    if (this.yPos > foodArray[index].y + foodHeight) { 
     this.speedY = -1 * Math.abs(this.speedY); 
    } else if (this.yPos < foodArray[index].y) { 
     this.speedY = Math.abs(this.speedY); 
    } 
}; 

我知道有一种方式,是通过计算精灵的点之间的直线的斜率该对象,以便让我的精灵图像移动。但尝试后,我仍然无法得到它。任何人都知道如何实现它?

回答

1

您canchange代码为chaseFood

以下
Fish.prototype.chaseFood = function (index) {  
    var tx = foodArray[index].x + foodWidth - this.xPos, 
     ty = foodArray[index].y + foodHeight - this.yPos, 
     dist = Math.sqrt(tx*tx+ty*ty); // better ways to do the distance. 

     // 1 can be any speed value to make it go faster or slower 
     this.speedX = (tx/dist)*1; 
     this.speedY = (ty/dist)*1; 
}; 

这样做是得到鱼和食品之间的距离,并且将当前的X,以及距离y分量使其朝行进食物以恒定的速度。你的总是1或-1,所以它会来回跳动,这种方法允许它是一个浮动,所以它可以准确地走向食物。

我改编了代码from an article on my blog其中有这种事情的其他有用的食谱。

Live Demo

+0

嗨,是有可能使精灵图像朝它游?而不是奇怪的移动方式。意味着鱼的嘴将面对食物和身体在后面。 – TypeB

+0

@Bernard是的,它涉及更多的数学。然而,你的问题和代码并没有真正表明:P如果你想要更多的信息如何做到这一点,请查看答案中的链接,而不是我*给你的codez!* – Loktar