问题
So I'm doing a little project in python using pyglet(opengl). When I click on a point in the screen a Square is generated that expands equally from the coordinate.
So for example if I click on (100,100) a square would be drawn from (99,99) with side length of 3. The bottom left point would decrease by (-1,-1) each generation and the side length increases by 2.
What I want to do is have a way to detect if the square is outside the boundaries of the window so I can delete it from my collection of squares.
What I'm doing now is just checking that all of the corners are inside the window, but there has to be a better way to do this? I have the side length, the center of the square and the bottom left point at my disposal.
Here's my square class, the method im looking at is the in_bounds method. Right now it's just returning true. Previously I was calculating each individual corner but I figure that using a single point with a length is better.
class Square:
def __init__(self, x, y, x_max, y_max):
self.center = (x,y)
self.point = (x-1, y-1)
self.length = 3
self.x_bound = x_max
self.y_bound = y_max
def next(self):
self.point = (self.point[0] - 1, self.point[1] - 1)
self.length += 2
def in_bounds(self):
return True
#return not (self.top_left[0] < 0 and self.top_right[0] > self.xbound and self.bot_left[1] < 0 and self.top_left[1] > self.ybound)
EDIT: My boundaries are going to be a rectangle.
回答1:
You can do it with just three points. Given a point inside the boundary (say top left) you can check that the top right point doesn't exceed the boundary in the positive x direction and that the lower left point doesn't exceed the negative y direction.
This assumes the boundary is square though. The fourth point can not exceed the length (x,y) of the points already measured.
来源:https://stackoverflow.com/questions/22205401/check-if-square-is-contained-in-another-square