Returning Objects from CollideImage()

BlitzMax Forums/BlitzMax Tutorials/Returning Objects from CollideImage()

Took me a while to get my head around this because CollideImage sort of has dual usage. Anyways, hopefully this will help you figure it out in minutes!

An example of using, and returning, Objects with CollideImage()

Graphics 640,480,0
AutoMidHandle True

Type ball
	Field image:timage
	Field name$

	Method New()
		Cls
		DrawOval 0,0,64,64
		image=CreateImage(64,64,1,DYNAMICIMAGE|MASKEDIMAGE)
		GrabImage image,0,0
	End Method
End Type

Local a:ball = New ball
Local b:ball = New ball
Local player:ball = New ball

a.name = "Ball a"
b.name = "Ball b"
player.name = "Ball player"

'cList is used to store a list of collided Objects
Local cList:Object[] = Null


SetBlend ALPHABLEND
		
While Not KeyHit(KEY_ESCAPE)
	Cls
	Local x%=MouseX()
	Local y%=MouseY()
	
	'Clear collision mask layer 1
	ResetCollisions(1)
	
	'Write image a.image into collision layer mask 1, and also store a link to Object a
	CollideImage a.image,50,50,0,0,COLLISION_LAYER_1,a
	DrawImage a.image,50,50

	'Write image b.image into collision layer mask 1, and also store a link to Object b
	CollideImage b.image,150,50,0,0,COLLISION_LAYER_1,b
	DrawImage b.image,150,50
	
	'Before we draw c.image, test if it will collide with anything in collision layer mask 1
	cList = CollideImage(player.image,x,y,0,COLLISION_LAYER_1,0)
	
	'Check the collision count
	If cList.length > 0
		'One or more collisions has happened!
		'change the alpha level as a visual indication
		SetAlpha .5
	Else
		SetAlpha 1.0
	End If
	
	'Draw player.image
	DrawImage player.image,x,y
	
	'Reset the alpha
	SetAlpha 1
	
	'Print a list of collision Objects names
	For Local i%=1 To cList.length
		'Remember, cList will contain Objects! We can cast them back to Types like so: ball(cList[x])
		'We could if needed check the Type of Object the player collided with using a cast check
		'If ball(cList[0]) = True 'cList[0] is a 'ball' Type
		DrawText("player.image collided with Object "+ball(cList[i-1]).name,5,150+(i*12))
	Next
	
	Flip
	
	'Free the old collision list
	cList = Null
	FlushMem
Wend