# Moving toward a Target in a Straight Line

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

## Recommended Posts

I am creating a simple 2D tile based game. It involves a character standing somewhere on the grid. When you click on spot in the grid it will set a target, the character will then move toward that target in a straight line. In order to accomplish this, I calculate the slope. This gives me a slope in decimal form which I normalize, then multiply times the speed of the sprite. This gives me a usable X/Y offset. So far so good, but I need the sprite to move while conforming to the tile map. I wan't the sprite to resolve which tile to move to based on the line I have calclulated. The resulting paths should be something similar to this: The red in this case shows the start location, and the green showes the target. This is the effect you usually see in a drawing program. How would I go about achiving this sort of pathing?

##### Share on other sites
delta.x = dest.x - start.xdelta.y = dest.y - start.ydistance = sqrt(delta.x*delta.x + delta.y*delta.y)delta.x = delta.x / distancedelta.y = delta.y / distance

Move by delta each time. TODO: Insert magic for dealing with fractions.

##### Share on other sites
All you need to do is store the position in floating point, but when you draw the sprite, round it to the nearest tile coordinate:

int((FloatX + (TileWidth / 2)) / TileWidth) * TileWidth;
Do the same for FloatX and TileHeight.

You might want to take out the (TileWidth / 2) term that does the rounding (that would change the operation to truncation) depending on how your system works.

##### Share on other sites
Quote:
 Original post by smart_idiot *** Source Snippet Removed ***Move by delta each time. TODO: Insert magic for dealing with fractions.

Hmmmm.... I like it. I just unearthed the "bresenham algorithm". It looks like a more complicated version of what you posted but optamized for speed.

The only problem I can see with yours is the calculation of the distance every time. This requires some sqrt() work and this is an arcade game so speed is a must.

I'll let you know how it goes ;)

##### Share on other sites
You only need to calculate the delta once, you can reuse it each test until you get where you're going (repreat for distance steps). But actually, using a line drawing algorithm like the one you just found is probably a better idea.

##### Share on other sites
Yep, this algorithem did it:

http://www.gamedev.net/reference/articles/article1275.asp

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 10
• 11
• 13
• 9
• 11
• ### Forum Statistics

• Total Topics
634091
• Total Posts
3015435
×