MiniB3D Sphere collision example

BlitzMax Forums/BlitzMax Programming/MiniB3D Sphere collision example

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

Yup. Just a quickie I needed for a project.
Just hacked it together from the primitives example :)

Control sphere with keys, it turns red when there's collision.

Here goes:

Import "MiniB3D.bmx"

Local width=640,height=480,depth=16,mode=0

Graphics3D width,height,depth,mode

Local  cam=CreateCamera()
PositionEntity cam,0,0,-10

Local light=CreateLight(1)

Local sphere=CreateSphere()
Local sphere2=CreateSphere()
PositionEntity sphere,-6,0,0
PositionEntity sphere2,-2,0,0
EntityColor sphere,255,255,255
EntityColor sphere2,255,255,255
EntityRadius sphere, 1
EntityRadius sphere2, 1

' Simple sphere collision
Function EntityCollide%(ent1:TEntity, ent2:TEntity)

	' Get relative pos
	Local relx:Float = EntityX(ent1) - EntityX(ent2)
	Local rely:Float = EntityY(ent1) - EntityY(ent2)
	Local relz:Float = EntityZ(ent1) - EntityZ(ent2)
	
	Local dist:Float = relx * relx + rely * rely + relz * relz
  	Local minDist:Float = ent1.radius + ent2.radius
  	Return dist <= minDist * minDist;	

End Function

Local cx#=0
Local cy#=0
Local cz#=0

Local pitch#=0
Local yaw#=0
Local roll#=0

' used by fps code
Local old_ms=MilliSecs()
Local renders
Local fps

While Not KeyDown(KEY_ESCAPE)		

	If KeyHit(KEY_ENTER) Then DebugStop

	' control camera

	If KeyDown(KEY_UP) Then cz#=cz#+1.0
	If KeyDown(KEY_LEFT) Then cx#=cx#-1.0
	If KeyDown(KEY_RIGHT) Then cx#=cx#+1.0
	If KeyDown(KEY_DOWN) Then cz#=cz#-1.0
	
	If KeyDown(KEY_W) Then pitch#=pitch#-1.0
	If KeyDown(KEY_A) Then yaw#=yaw#+1.0
	If KeyDown(KEY_S) Then pitch#=pitch#+1.0
	If KeyDown(KEY_D) Then yaw#=yaw#-1.0

	MoveEntity sphere,cx#*0.5,cy#*0.5,cz#*0.5
	RotateEntity sphere,pitch#,yaw#,roll#
	
	cx#=0
	cy#=0
	cz#=0

	If (EntityCollide(sphere, sphere2))
	
		EntityColor(sphere, 255, 0, 0)
	
	Else
	
		EntityColor(sphere, 255, 255, 255)

	End If
	
	
	cx#=0
	cy#=0
	cz#=0

	RenderWorld
	renders=renders+1

	' calculate fps
	If MilliSecs()-old_ms>=1000
		old_ms=MilliSecs()
		fps=renders
		renders=0
	EndIf
	
	DebugText 0,0,"FPS: "+String(fps)

	Flip

Wend
End