Jump to content
  • Advertisement

Archived

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

Gf11speed

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.

If you intended to correct an error in the post then please contact us.

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 this post


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

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

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!