Blitz3D+ Command Reference

Sqr# ( float# )

Parameters

float - the number to take the square root of; should be zero or positive

Description

Returns the square root of a number.

Sqr is the distance command in disguise. The gap between two points is Sqr( dx*dx+dy*dy ) in 2D, or Sqr( dx*dx+dy*dy+dz*dz ) in 3D - the basis of every proximity check, pickup radius and enemy aggro range you will write.

It always returns a float, even when you hand it an integer, so assign it to a variable with a # suffix or you will lose the fractional part.

A speed tip: square roots are not free. When you only need to compare distances - "is this enemy closer than that one", "am I within 5 units" - skip the Sqr and compare the squared distances instead. Sqr( d ) < 5 is the same test as d < 25, and the second one is cheaper.

Negative input has no real square root and returns NaN (not a number), so guard any value that could go below zero.

See also: Exp, Log, Abs, Floor.

Example

; Sqr Example
; -----------

; Sqr returns the square root of a value, always as a float.

Print "Sqr(25)  = "+Sqr(25)
Print "Sqr(100) = "+Sqr(100)
Print "Sqr(2)   = "+Sqr(2)
Print "Sqr(0.25) = "+Sqr(0.25)

Print ""

; Classic game use: the straight-line distance between two points
x1=100
y1=100
x2=400
y2=340
dx=x2-x1
dy=y2-y1
Print "From ("+x1+","+y1+") to ("+x2+","+y2+")"
Print "Distance = Sqr(dx*dx+dy*dy) = "+Sqr(dx*dx+dy*dy)

Print ""
Print "Press any key to close the example"
WaitKey

End

Index