0

I am trying to figure out a mathematical way to identify if a point lies inside a polygon that I draw with turtle. I am trying to only use turtle and math library to achieve this. I am not using classes either.

However the problem I am facing with the Ray casting method for example is that this means would I have to store equation of line of every side of polygon that I draw into a list before I can cast a line with my input point and check for intersection line by line? Or is there a more efficient way to do this? Unfortunately turtle does not have collision detection so I cannot do it that way.

1 Answers1

0

You state that you only want to use the math module but you might be able to find some pointers from the source code of mathplotlib. Here is how to do this with mathplotlib.path. I added the turtle part to make it a little more interesting.

import turtle
import matplotlib.path as mplPath

t1 = turtle.Turtle()

polygon_points = [[0, 0],
        [100, 0],
        [100, 100],
        [0, 100],
        ]
  
t1.penup()
t1.speed(0)
t1.hideturtle()
  
for point in polygon_points:
    t1.setposition(point)
    t1.pendown()

t1.home()
t1.penup()

poly_path = mplPath.Path(polygon_points)
point = (20, 20)
t1.setposition(point)
string1 = str(point) + " in polygon: " + str(poly_path.contains_point(point))
t1.write(string1)

point = (120, 50)
t1.setposition(point)
string1 = str(point) + " in polygon: " + str(poly_path.contains_point(point))
t1.write(string1)

turtle.done()

The result looks like this: Turtle example output

Another possibility is to use numpy as demonstrated here. That thread also has a demonstration of finding the intersection of two lines using determinates.

FractalLotus
  • 350
  • 2
  • 11