GLBasic forum

Codesnippets => Code Snippets => Topic started by: SBlectric on 2011-Dec-27

Title: 3D Distance
Post by: SBlectric on 2011-Dec-27
2nd post...
For any 3D game you need to know the distance between two objects, there is this function I made:

Code (glbasic) Select

FUNCTION Distance3D: x1,y1,z1, x2,y2,z2
RETURN SQR( POW(x2-x1,2) + POW(y2-y1,2) + POW(z2-z1,2) )
ENDFUNCTION


Enjoy!
Title: Re: 3D Distance
Post by: Kitty Hello on 2011-Dec-27
instead of POW(x2-x1, 2), you might want to use a temp variable, because the POW function is very CPU expensive.
(POW(n, 0.5) is a square root, so POW is at least slower than SQR)
Code (glbasic) Select

LOCAL dx = x2-x1
RETURN SQR( (dx*dx) + ...
Title: Re: 3D Distance
Post by: SBlectric on 2011-Dec-27
Oh OK I see. So something like this would be faster:

Code (glbasic) Select

FUNCTION Distance3D: x1,y1,z1,  x2,y2,z2
LOCAL a=(x2-x1)
LOCAL b=(y2-y1)
LOCAL c=(z2-z1)
RETURN SQR(a*a+b*b+c*c)
ENDFUNCTION