Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Point-in-Polygon Detection
#1
Code: (Select All)

_Title "Polygon collision detection"
Type Vertex2D
    As Integer x, y
End Type
Const PolyVertexes = 8

Dim Polygon(1 To PolyVertexes) As Vertex2D

Screen _NewImage(1000, 1000, 256)

NextPoly:
Polly_MidX = 100 + 890 * Rnd
Polly_MidY = 100 + 890 * Rnd
StepAngle = _Pi(2) / PolyVertexes
StartAngle = StepAngle * (Rnd * PolyVertexes)

For fillP = 1 To PolyVertexes
    If Rnd * 10 > 4 Then Sign = -1 Else Sign = 1
    Radius = 70 + Sign * Rnd * 50
    Angle = StartAngle + StepAngle * fillP
    Polygon(fillP).x = Polly_MidX + Cos(Angle) * Radius
    Polygon(fillP).y = Polly_MidY + Sin(Angle) * Radius
Next

Dim As Long K
Draw_Polygon Polygon()
Do Until K = 32
    K = _KeyHit
    While _MouseInput: Wend
    mx = _MouseX: my = _MouseY
    Locate 1
    Print "Press space for next polygon, ore esc for end"
    Print "Colission detection - Polygon / mouse: "; DetectPolygon(Polygon(), mx, my)
    If K = 27 Then End
Loop
K = 0
Cls
GoTo NextPoly







Sub Draw_Polygon (polygon() As Vertex2D)
    PSet (polygon(1).x, polygon(1).y)
    For DP = 1 To PolyVertexes
        Line -(polygon(DP).x, polygon(DP).y)
        MiddleX = MiddleX + polygon(DP).x
        MiddleY = MiddleY + polygon(DP).y
    Next DP
    Line (polygon(DP - 1).x, polygon(DP - 1).y)-(polygon(1).x, polygon(1).y)
    MiddleX = MiddleX \ PolyVertexes
    MiddleY = MiddleY \ PolyVertexes
    Paint (MiddleX, MiddleY), Rnd * 254 + 1, 15
End Sub

Function DetectPolygon (polygon() As Vertex2D, mx, my)
    inside = 0

    For i = 1 To PolyVertexes
        j = i + 1
        If j > PolyVertexes Then j = 1 ' if connects the last point to the first

        yi = polygon(i).y
        yj = polygon(j).y
        xi = polygon(i).x
        xj = polygon(j).x

        'Test if horizontal ray intersects edge (i -> j)
        If (yi > my) <> (yj > my) Then
            crossX = xi + (my - yi) * (xj - xi) / (yj - yi)
            If mx < crossX Then inside = Not inside
        End If
    Next i
    DetectPolygon = inside
End Function


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Detect point in triangle (2D) Petr 2 874 11-20-2024, 07:31 PM
Last Post: Petr

Forum Jump:


Users browsing this thread: 1 Guest(s)