#### Archived

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

# Linear movement?

This topic is 5764 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 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 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 on other sites
Thanks AlanKemp, that code works fine for what I''m doing.

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 16
• 12
• 20
• 12
• 13
• ### Forum Statistics

• Total Topics
632155
• Total Posts
3004474

×