# How do I make a game object move at an angle in an integer-indexed grid? [duplicate]

I'm making a game in SDL2 and C++. I want a way to make any game object move in a specific direction. I've thought of assigning each object a direction in radians, from 0 until 2 PI where 0 would represent movement in the positive x direction, and PI movement in the negative x direction (0.5 PI would be positive y, 1.5 PI negative y, etc).

My problem occurs when trying to translate these directions into actually moving an object on the screen - moving objects with directions of 0, 0.25 PI, 0.5 PI, 0.75 PI, etc are trivial, as one would either decrement or increment only x, or only y, or alternate x and y.

To approximate other angles of movement in x and y, I figured I could calculate how much each object should move in x, before it increments y, (or vice versa, depending on whether the direction is bigger or smaller than 0.25 PI, and assuming we're only considering the positive x and y quadrant ). And then restricting how many moves in x and y the object makes each time it is moved, in an attempt to preserve the speed of the object, though this would still result in an object moving along an axis moving slower than one moving in at an angle. Is this a reasonable solution?

Is there a more elegant or precise way of accomplishing this problem?

• As you're computing an angle in radians and know (I think) what is the total distance of the movement; can't you easily compute both x and y components of the line segment between your entity's origin and the movement destination? – user43240 Mar 11 '14 at 14:59
• The trouble with that, is that given the object moves 2 pixels at a time, calculating the x and y components of multiple tiny triangles does not offer enough precision. I would have to project a larger triangle, and then move a fraction of that each time the entity moves. Really, I want to know how to approximate lines of different gradients to a pixel grid. – PointToPoint Mar 11 '14 at 15:16
• It sounds like you basically are asking about Bresenham's line? – user1430 Mar 11 '14 at 15:37
• I'm confused; is this a tile-based game? – Anko Mar 11 '14 at 16:00