News:

Function Finder  Find all the functions within source code files

Main Menu

Finding Closest Objects Example

Started by kevin, March 19, 2014, 09:34:33 PM

Previous topic - Next topic

kevin


Finding Closest Objects Example

   

PlayBASIC Code: [Select]
   Type tCharacter
x#,y# ; world position
colour
nearestcharacter
EndType


Dim Character(10) as tCharacter


Init_Scene()

; ---------------------------------------------------------------------------
; ---[ MAIN LOOp ]-----------------------------------------------------------
; ---------------------------------------------------------------------------

; make a camer to view the scene with
cam=newcamera()

Do
cls


if Spacekey()
Init_Scene()
flushkeys
endif

; find what characters are closest to what charcters
Resolve_Closest_Characters()


; draw the scene
Draw_Characters()


drawcamera cam

Sync
loop esckey()


end



Function Init_Scene()


For lp=1 to 10
Character(lp) = new tCharacter

; give this character a random position
Character(lp).x=rnd(800)
Character(lp).y=rnd(600)
Character(lp).colour= rnd($ffffff)
Character(lp).nearestcharacter =-1
next



EndFunction


; ---------------------------------------------------------------------------
; ---[ Resolve Closest Characters ]------------------------------------------
; ---------------------------------------------------------------------------


Function Resolve_Closest_Characters()

for lp=1 to GetArrayElements(Character())
if Character(lp)
; find the character that is closest to this character
Character(lp).nearestcharacter =Find_Closest_Characters_To_Character(lp)
endif
next

EndFUnction


; ---------------------------------------------------------------------------
; ---[ Finde Closest Character To Character ]------------------------------------------
; ---------------------------------------------------------------------------

Function Find_Closest_Characters_To_Character(TargetCharacter)

ClosestID=-1
ClosestDistance=1000000

PointX=character(TargetCharacter).x
PointY=character(TargetCharacter).y

for lp=1 to GetArrayElements(Character())
if TargetCharacter<>lp
if Character(lp)
dist=getdistance2d(character(lp).x,character(lp).y,pointX,pointY)
if Dist<ClosestDistance
ClosestDistance=Dist
ClosestID=LP
endif
endif
endif
next

EndFUnction ClosestID


Function Draw_Characters()

capturetoscene
clsscene
for lp=0 to GetArrayElements(Character())
if Character(lp)
x =Character(lp).x
y =Character(lp).y
col =Character(lp).colour
ClosestID=Character(lp).nearestcharacter

capturedepth 100
circlec x,y,30,true,col

; ClosestID
if ClosestID>0
Targetx =Character(ClosestID).x
Targety =Character(ClosestID).y
capturedepth 50

LineC x,y,TargetX,TargetY,$00ff00
endif

capturedepth 10
centertext x,y,"Me#"+Digits$(lp,2)+" -> "+digits$(ClosestID,2)

endif
next

EndFUnction