Sign in to follow this  
Andreas Persson

per pixel collision calculating start position

Recommended Posts

Hi I am currently implementing per pixel collision into my project. I have calculated the collision box where the overlap occur. I now need to get the part in my sprites where this box is positioned. So how do I calculate where the box is in the two sprites? Best Regards Andreas

Share this post


Link to post
Share on other sites
Here is some code from something I wrote just the other day:
	Dim As Integer x1,y1,x2,y2,Aw=_maskA.sprite->Width,Ah=_maskA.sprite->height,Bw=_maskB.sprite->width,Bh=_maskB.sprite->height
Dim As UInteger oAx,oAy,oBx,oBy
Dim As UInteger maxA,minA,maxB,minB
Select Case _Ax-_Bx
Case Is >0
If (_Ax>=_Bx+Bw)Then Return 0 'boxes don't overlap.
x1=_Ax
oAx=0
oBx=x1-_Bx
Case Is <=0
If (_Bx>=_Ax+Aw)Then Return 0 'boxes don't overlap.
x1=_Bx
oBx=0
oAx=x1-_Ax
End Select
' Print "1"
Select Case _Ay-_By
Case Is >0
If (_Ay>=_By+Bh)Then Return 0 'boxes don't overlap.
y1=_Ay
oAy=0
oBy=y1-_By
Case Is <=0
If (_By>=_Ay+Ah)Then Return 0 'boxes don't overlap.
y1=_By
oBy=0
oAy=y1-_Ay
End Select
' Print "2"
Select Case (_Ax+Aw)-(_Bx+Bw)
Case Is <=0
If (_Ax+Aw<=_Bx)Then Return 0 'boxes don't overlap.
x2=_Ax+Aw
Case Is >0
If (_Bx+Bw<=_Ax)Then Return 0 'boxes don't overlap.
x2=_Bx+Bw
End Select
' Print "3"
Select Case (_Ay+Ah)-(_By+Bh)
Case Is <=0
If (_Ay+Ah<=_By)Then Return 0 'boxes don't overlap.
y2=_Ay+Ah
Case Is >0
If (_By+Bh<=_Ay)Then Return 0 'boxes don't overlap.
y2=_By+Bh
End Select
' Print "4"
Dim As Integer dx=x2-x1,dy=y2-y1
If (dx<0)or(dy<0)Then
Return 0 'no collision
EndIf

Notes:
' is the comment mark.
Select case/end case is a switch.
_Ax,_Ay is the position of the first sprite in the scene.
_Bx,_By is the position of the second sprite in the scene.
(x1,y1),(x2,y2) is the collision rectangle.
oAx,oAy are the offsets of where the collision box is located in the first sprite.
oBx,oBy are the offsets of where the collision box is located in the second sprite.

Return 0= no collision
Return -1 = collision (there is no return -1 in the above code :P)

I hope that helps ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this