Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Here's how to find the distance between 2 points — Gideros Forum

Here's how to find the distance between 2 points

Tom2012Tom2012 Guru
edited November 2012 in Code snippets
Had this in my folder of notes for a while and it's pretty useful.

The math is:

distance between = square root of distanceX² + distanceY²

In this example, the code is added to a bullet and hero is the main character.
-- Get distance between x points
 
self.dx = self:getX() - self.scene.hero:getX();
 
-- get distance between y points
 
self.dy = self:getY() - self.scene.hero:getY();
 
self.distance = math.sqrt((self.dx*self.dx)+(self.dy*self.dy))

Comments

  • techdojotechdojo Guru
    edited November 2012
    You can avoid the nasty (expensive) math.sqrt function by just pre-squaring the distance you want to check against,

    so if you want to check if an object is within say 25 pixels instead of checking if self.distance <= 25, just set self.distance = ((self.dx * self.dx) + (self.dy * self.dy)) and then check if self.distance <= (25*25).

    If you've got a lot of checks to do the savings will start to mount up.

    Also - there used to be a quick hack in the old 8/16bit days where you could "guestimate" distance to +/-10% by calculating dx and dy as above and then simply using the max of dx or dy plus half the min of dx or dy, using a single bit shift right the "half" practically came for free.

    Likes: talis, plamen

    WhiteTree Games - Home, home on the web, where the bits and bytes they do play!
    #MakeABetterGame! "Never give up, Never NEVER give up!" - Winston Churchill
    +1 -1 (+2 / -0 )Share on Facebook
  • Tom2012Tom2012 Guru
    edited November 2012
    Hey techdojo

    That works perfectly. Thank you.

    For anyone interested, here's my example:

    (self.maxLength is the max length in this example)
    -- Work out the distance from hero
     
    self.dx = self:getX() - self.scene.hero:getX();
    self.dy = self:getY() - self.scene.hero:getY();
     
    self.distance = (self.dx*self.dx)+(self.dy*self.dy)
     
    -- Distance went over maxLength
     
    if(self.distance >= (self.maxLength*self.maxLength)) then
     
    -- do something here
     
    end

    Likes: techdojo, talis

    +1 -1 (+2 / -0 )Share on Facebook
  • @Tom2012 thanks for the share :)
    ThumbHurt Games / FB: ThumbHurt Games / FB: Eli/Teranth | Skype: teranth37
  • Thanks for the share guys:-)
Sign In or Register to comment.