Sprite Collision With An Image Mask

Started by kevin, August 31, 2008, 11:41:18 AM

Previous topic - Next topic

kevin

Sprite Collision With An Image Mask

  This example shows how you can use ImageHitSpritePixels for pixel based collision against a collision mask.  


PlayBASIC Code: [Select]
   sw=GetScreenWidth()
sh=GetScreenHeight()

global CollisionMask=NewFXIMage(sw,sh)

// Draw some circles for some collision hot spots
rendertoimage CollisionMask
for lp=0 to 50
circle rnd(sw),rnd(sh),50,true
next

// clear our a chunk where the player is going to be dropped
circlec sw/2,sh/2,100,true,rgb(0,0,0)


; Create player image.. In this demo the player is a blue circle
PlayerImage=newFXImage(64,64)
rendertoimage PlayerImage
circlec 32,32,32,true,255
rendertoscreen

; Create player sprite
PlayerSpeed#=5
PLayer=NewSprite(sw/2,sh/2,PLayerImage)
SpriteDrawMode PLayer,2
SpriteCollisionMode Player,6
SpriteCollisionDebug Player,off


; Main loop
Setfps 60
Do
; set the cursor
setcursor 0,0

; Draw the backdrop
c1=rgb(20,230,140)
c2=rgb(120,30,40)
shadebox 0,0,sw,sh,c1,c2,c1,c2

; Draw the collision Mask image so we can see what we're hitting
DrawImage CollisionMask,0,0,true

; handle moving the player
MoveX#=(Leftkey()*-PLayerSpeed#) + (Rightkey()*PlayerSpeed#)
MoveY#=(Upkey()*-PLayerSpeed#) + (Downkey()*PlayerSpeed#)
MOveMe(Player,MoveX#,MoveY#)

; draw the sprites
drawAllSprites

; refresh the screen and loop back to the DO statement.
Sync
loop


Function MOveMe(ThisSprite,MoveX#,MoveY#)
SpriteTint ThisSprite,$ffffff

if Movex#=0 and Movey#=0 then exitfunction

// Get it's current position
BaseX#=GetSpriteX(ThisSprite)
BaseY#=GetSpriteY(ThisSprite)
x#=BaseX#+MoveX#
y#=BaseY#+MoveY#
positionSprite ThisSprite,x#,y#


; Check if this position hits the collision mask
if ImageHitSpritePixels(CollisionMask,0,0,ThisSprite,1)
SpriteTint ThisSprite,rndrgb()

// iof it did, try and resolve
dist=GetDistance2d(0,0,movex#,movey#)
if Dist>0
nx#=moveX#/dist
ny#=movey#/dist

X#=BaseX#
Y#=BaseY#
for lp=1 to Dist
positionSprite ThisSprite,Basex#+(lp*nx#),Basey#+(lp*ny#)
if ImageHitSpritePixels(CollisionMask,0,0,ThisSprite,1)=true
x#=Basex#+((lp-1)*nx#)
y#=Basey#+((lp-1)*ny#)
exitfor
endif
next
endif
positionSprite ThisSprite,x#,y#
endif

EndFunction






  Notes:

       * This is old code, It's generally a better idea to use MAPS today.   CircleHitMap / CircleHitMapPixels commands added to  PlayBASIC V1.64N2 / V164N3 (Work In Progress) Gallery