Napivo1972
Well-known member
- Joined
- Aug 31, 2004
- Messages
- 75
Apparently we are still missing a nice pixel perfect collision detection her so I tried to make one myself (with some help from the C examples.
From what I understand I need to calculate where the 2 rectangles overlap and the test if the pixels are not transparent. When both pixels are not transparent I have a collision.
From what I understand I need to calculate where the 2 rectangles overlap and the test if the pixels are not transparent. When both pixels are not transparent I have a collision.
Code:
Namespace Collision
Public Class PixelPerfectCollisionDetection
Public Shared Function PixelPerfectCollisionDetection(ByVal obj1 As BaseObject, ByVal obj2 As BaseObject) As Boolean
Dim tRect As Rectangle
Dim tPoint1 As Point
Dim tPoint2 As Point
Dim color1 As Color
Dim color2 As Color
Dim t1, t2 As Integer
tRect = Rectangle.Intersect(obj1.Rect, obj2.Rect)
If tRect.Width = 0 AndAlso tRect.Height = 0 Then Return False rectangles dont overlap
tPoint1 = Substract(New Point(tRect.X, tRect.Y), obj1.Rect) Normalize rectange1
tPoint2 = Substract(New Point(tRect.X, tRect.Y), obj2.Rect) Normalize rectange2
For t1 = 1 To tRect.Width
For t2 = 1 To tRect.Height
Console.WriteLine("x = {0} y = {1}", obj1.BMP.Height, obj1.BMP.Width)
color1 = obj1.BMP.GetPixel(tPoint1.Y + t1, tPoint1.X + t2) Invalid parameter used. here (Not always but sometimes)
If color1.ToArgb <> obj1.transparent.ToArgb Then
color2 = obj2.BMP.GetPixel(tPoint1.X + t1, tPoint1.Y + t2) Probably same problem here
If color2.ToArgb <> obj2.transparent.ToArgb Then
Return True
End If
End If
Next
Next
End Function
Private Shared Function Substract(ByVal point As Point, ByVal Rect As Rectangle) As Point
Dim tPoint As Point
tPoint.X = (Rect.X - point.X)
tPoint.Y = (Rect.Y - point.Y)
Return tPoint
End Function
End Class
End Namespace