Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving an object towards a point in javascript [closed]

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.

like image 251
wazzaday Avatar asked Dec 24 '13 13:12

wazzaday


3 Answers

First, determine the angle of approach using atan2.

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

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

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

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.)

like image 186
Kevin Avatar answered Oct 29 '22 13:10

Kevin


First you compute the delta between the source point and the destination point:

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

Then you compute the angle between the two points with the atan2 function:

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

Now that you have the angle you can compute the velocity vector through magnitude (1) and the angle:

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

Don't mix up magnitude with the sum of components of a vector, the formula v.x + v.y = 1.0 is not correct, because the magnitude is the square root of the sum of squared components so the correct formula would be Math.sqrt(v.x*v.x + v.y*y.y) = 1

like image 25
Jack Avatar answered Oct 29 '22 14:10

Jack


You need to do this:

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, same with y, then calculate the total of thos difference and divide x/y by it !

See this fiddle for an example

like image 30
Shryme Avatar answered Oct 29 '22 12:10

Shryme