Moving an object to a point in javascript

I struggle with math for this, I need to move the object evenly to a point. I have a point at x: 500 y: 250 and an object at 0,0. With the speed of movement "1", how would I figure it out to get this point, I would need to move at a speed of x: 0.666 and y: 0.333. The speed y is half the speed x. I'm sure I'm just an absolute idiot here.

+4
source share
3 answers

First, determine the approach angle using atan2.

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

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

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

xVelocity, 0,8944, yVelocity, 0,472, . ( 0,666 0,333 , 0,745.)

+6

:

var dx = destX - srcX;
var dy = destY - srcY;

atan2:

var angle = Math.atan(dy, dx);

, , (1) :

var magnitude = 1.0;
var velX = Math.cos(angle) * magnitude;
var velY = Math.sin(angle) * magnitude;

, v.x + v.y = 1.0 , , Math.sqrt(v.x*v.x + v.y*y.y) = 1

+5

:

function calculateSpeed(x1, y1, x2, y2)
{
    x = x2 - x1;
    y = y2 - y1;
    total = x + y;

    speedX = x / total;
    speedY = y / total;

    alert("x: " + speedX + " y: " + speedY);
}

So, you need to calculate the difference between the point x1 and x2, the same with y, then calculate the total number of differences and divide x / y by it!

See fiddle for an example.

+2
source

All Articles