0

I have a 2D vision cone and I want to check if a rectangle intersects it. How can I do this? Like in this picture the cone and the rectangle intersect:

img

Spektre
  • 49,595
  • 11
  • 110
  • 380
John
  • 41
  • 1
  • 7
  • Calculate intersection of rectangle with circle. If it exists, check whether intersection lies in sector angle range. – MBo May 27 '22 at 14:21
  • @MBo Can you be more specific? What intersection point(s) exactly? Do you mean intersections between the circle periphery and the rectangle (of which there can be between 0 and 4) then that won't work since none of those need to be within the sector angle. Do you mean the closest point between the circle and the rectangle? That won't work either, similar reason. – John May 27 '22 at 15:01
  • At first - intersection with circumference. if yes - check sector arc and sector sides. Also look at exotic cases like whole rectangle inside sector, all sector inside rectangle. – MBo May 27 '22 at 15:13
  • see very similar question [Detect if a cube and a cone intersect each other?](https://stackoverflow.com/a/22066312/2521214) and this [Generate a "pieslice" in C without using the pieslice() of graphics.h](https://stackoverflow.com/a/58246614/2521214) – Spektre May 28 '22 at 06:47

1 Answers1

0

I would like to provide an answer using the shapely Python library.

Import relevant libraries:

import matplotlib.pyplot as plt
from shapely.geometry import Polygon, Point, LineString, MultiLineString

Create the rectangle (you will have to modify its vertex coordinates):

rectangle = Polygon([(0.5, 0), (4, 0), (4, 2), (0.5, 2)])

Create the circular sector (you will have to modify its aperture angle and position):

# Create a circle whose radius is given by the buffer argument.
circle = Point(0, 0).buffer(1.0)

# Create two lines to cut the circle into a sector.
a = LineString([(0, 0), (1, 1)])
b = LineString([(0, 0), (1, -1)])
multi_line = MultiLineString([a, b])
line_poly = multi_line.convex_hull

# Intersect the two lines with the circle
circular_sector = circle.intersection(line_poly)

Let's have a look at the rectangle and circular sector:

plt.plot(*circular_sector.exterior.xy)
plt.plot(*rectangle.exterior.xy)
plt.gca().set_aspect('equal', adjustable='box')

enter image description here

Check if the two shapes intersect with each other:

>>> print(circular_sector.intersects(rectangle))
True

The result is True.

Let's examine other cases (for the sake of simplicity I am going to modify the rectangle only):

No intersection

rectangle = Polygon([(1.5, 0), (4, 0), (4, 2), (1.5, 2)])
>>> print(circular_sector.intersects(rectangle))
False

enter image description here

Whole rectangle inside the sector

rectangle = Polygon([(0.2, 0.0), (0.5, 0.0), (0.5, 0.1), (0.2, 0.1)])
>>> print(circular_sector.intersects(rectangle))
True

enter image description here

blunova
  • 2,122
  • 3
  • 9
  • 21