#### Archived

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

# From Point A to Point B?

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

## Recommended Posts

This may seem like a dumb question, and I know its been done many times before, but I can''t get my sprite to take the best path between two points. Right now I do something like this:  if(sprite.x < ptX) sprite.x++; if(sprite.x > ptX) sprite.x--; if(sprite.y < ptY) sprite.y++; if(sprite.y > ptY) sprite.y--;  This works, however, it doesn''t take the best path to the object. For example, if the X distance is smaller than the Y distance, then the sprite will only be moving along the Y coord for a set amount of time. I can''t seem to figure out how to get it to take the best path. Any suggestions? Thanks. *====================* http://www.syntasoft.com *=======================*

##### Share on other sites
google for bresenham line algorithm sourcecode, it''ll do exactly what you want.

2DNow - Specializing in yesterday''s technology today!

##### Share on other sites
I see.. so.. a line is the shortest distance between two objects?

##### Share on other sites
Actually, if your character can only go up, down, left, or right, following a line using the bresenham line algorithm won''t be any quicker than the way it is going now.

##### Share on other sites
A simple algorithm to go down the middle is this:

(assuming up, down, left, right restriction)

  if (abs(sprite.x - ptX) > abs(sprite.y - ptY)) {	sprite.x += (sprite.x > ptX)? -1 : 1;} else if (abs(sprite.y - ptY) > abs(sprite.x - ptX) {	sprite.y += (sprite.y > ptY)? -1 : 1;} else {	if (rand()%2) {		sprite.x += (sprite.x > ptX)? -1 : 1;	} else {		sprite.y += (sprite.y > ptY)? -1 : 1;	}}

##### Share on other sites
I got it... thanks guys.

*====================*
http://www.syntasoft.com
*=======================*

1. 1
Rutin
42
2. 2
3. 3
4. 4
5. 5

• 9
• 27
• 20
• 14
• 14
• ### Forum Statistics

• Total Topics
633388
• Total Posts
3011617
• ### Who's Online (See full list)

There are no registered users currently online

×