将对象移到javascript中的某个点

问题描述:

为此我在数学上苦苦挣扎,我需要将一个对象均匀地移向某个点.我在x:500 y:250有一个点,在0,0有一个对象.当移动速度为"1"时,如何计算出该点,我将需要以x:0.666和y:0.333的速率移动. y速度是x速度的一半.我确定我只是这里的白痴.

Im struggling with the maths for this, I need to move an object evenly towards a point. I have a point at x:500 y:250 and an object at 0,0. With a movement speed of '1' how would I work out that to get the that point I would need to move at a rate of x:0.666 and y:0.333. The y speed being half of the x speed. Im sure i am just being an absolute idiot here.

首先,使用atan2确定接近角度.

First, determine the angle of approach using atan2.

dx = 500 - 0;
dy = 250 - 0;
angle = atan2(dy, dx)

使用角度,您可以将速度分解为其x和y分量.

Using the angle, you can decompose your velocity into its x and y components.

xVelocity = velocity * cos(angle);
yVelocity = velocity * sin(angle);

对于您的示例问题,这将使xVelocity等于0.8944,而yVelocity等于0.4472,看起来很正确. (您最初对0.666和0.333的猜测是不正确的,因为那样的话,您的总移动速度将为0.745.)

For your example problem, this will give xVelocity equal to 0.8944 and yVelocity equal to 0.4472, which looks about right. (Your initial guess of 0.666 and 0.333 isn't accurate, since then your total movement speed would be 0.745.)