Archived

This topic is now archived and is closed to further replies.

Faze

Linear movement?

Recommended Posts

Can anyone give me a sample algorithm on how to make an object move in a straight line on a 2D plane? So far, my game moves the object in a diagonal line until it reaches the same X or Y position, then moves it along a straight line. I need an alogorithm that will make the object move in a diagonal line until it reaches the destination. Ideas?

Share this post


Link to post
Share on other sites
We can find a 2d vector (the direction we should travel) by calculating the distance to travel along each of the x and y axis, and then normalising the result.

dist_x = dest_x - start_x;
dist_y = dest_y - start_y;

length = sqrt(dist_x*dist_x + dist_y*dist_y);
amount_to_move_x = dist_x / length;
amount_to_move_y = dist_y / length;

Now every frame just move your object by these values (multiplied by the objects velocity if required).

Object.x += (amount_to_move_x * Object.velocity);
Object.y += (amount_to_move_y * Object.velocity);


Hope this helps,

Alan

Share this post


Link to post
Share on other sites
A basic method would be, at each step, to take vectors representing the degrees of freedom and performing a dot product with each of those against a vector representing the destination. Then move in the direction with the largest dot product. Just be sure to normalize the direction vectors, if you want natural looking movement.

Alternately you could try using Bresenham''s line algorithm. A write up of it is available in the graphics section of the resources here on gamedev.

Share this post


Link to post
Share on other sites