• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • 🏆 Hive's 6th HD Modeling Contest: Mechanical is now open! Design and model a mechanical creature, mechanized animal, a futuristic robotic being, or anything else your imagination can tinker with! 📅 Submissions close on June 30, 2024. Don't miss this opportunity to let your creativity shine! Enter now and show us your mechanical masterpiece! 🔗 Click here to enter!

[Solved] Distance calculation vs. DistanceBetweenPoints

Status
Not open for further replies.
Level 11
Joined
Dec 21, 2012
Messages
373
Hello there. I've recently happened upon a formula for calculating distance between two points using coordinates:
Distance = |P-E| = |(3,3)-(1,2)| = |(2,1)| = sqrt(22+12) = sqrt(5) = 2.23
("P" and "E" stand for the two points)
I was wondering, if this...

JASS:
    local real x
    local real y
    local real x2
    local real y2
    local real a
    local real b
    local real dist
    local unit u1 = gg_unit_hkni_0001
    local unit u2 = gg_unit_hkni_0002

    set x = GetUnitX(u1)
    set y = GetUnitY(u1)
    set x2 = GetUnitX(u2)
    set y2 = GetUnitY(u2)

    set a = (x2 - x)
    set b = (y2 - y)

    set dist = SquareRoot(a*a + b*b)

...Gives any significant advantage over simply using DistanceBetweenPoints in JASS? I've always been simply using the function, but if this is the better way...
 
The code you showed is basically the same as DistanceBetweenPoints except that it doesn't use locations. Locations should rarely be used, if at all, anyways.

JASS:
function DistanceBetweenPoints takes location locA, location locB returns real
    local real dx = GetLocationX(locB) - GetLocationX(locA)
    local real dy = GetLocationY(locB) - GetLocationY(locA)
    return SquareRoot(dx * dx + dy * dy)
endfunction
 
Level 39
Joined
Feb 27, 2007
Messages
5,031
Additionally, if you care about performance the bottleneck is going to be the sqrt() function. Instead of taking the sqrt and comparing the distance to some number D, leave out the sqrt and compare the 'distance squared' to D*D. This is not generally a problem, but if you are doing many computations per second it can be worth it.

JASS:
function IsLessThanWithSqrt takes real x1, real y1, real x2, real y2, real dist returns boolean
    return Sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)) <= dist
endfunction

function IsLessThanNoSqrt takes real x1, real y1, real x2, real y2, real dist returns boolean
    return (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) <= dist*dist
endfunction
 
Level 11
Joined
Dec 21, 2012
Messages
373
So it is slightly advantageous then, I guess. Thanks for the answers. And I will definitely try it out, Pyro. Thanks.
 
Status
Not open for further replies.
Top