Reputation: 159
I have a problem about rotated rect collision.
Here is my Car class:
class Car:
def __init__(self,x,y):
self.x = x
self.y = y
self.default_image = pygame.image.load("car.png")
self.image = self.default_image
self.w = self.image.get_size()[0]
self.h = self.image.get_size()[1]
self.right_image = pygame.transform.rotate(self.default_image, -10)
self.left_image = pygame.transform.rotate(self.default_image, 10)
self.rot = 0
def render(self):
screen.blit(self.image,self.getRect())
def getRect(self):
return self.default_image.get_rect(center=(self.x,self.y))
def getMask(self):
return Polygon(calculate(self.getRect(),self.rot))
def right(self):
self.rot = -10
self.image = self.right_image
def left(self):
self.rot = 10
self.image = self.left_image
def default(self):
self.rot = 0
self.image = self.default_image
def drawHitbox(self):
pygame.draw.lines(screen,(242, 236, 12),True,calculate(self.getRect(),self.rot),1)
Here is my 'calculate' function:
def calculate(irect,angle):
pivot = math.Vector2(irect[0],irect[1])
p0 = (math.Vector2(irect.topleft) - pivot).rotate(-angle) + pivot
p1= (math.Vector2(irect.topright) - pivot).rotate(-angle) + pivot
p2 = (math.Vector2(irect.bottomright) - pivot).rotate(-angle) + pivot
p3 = (math.Vector2(irect.bottomleft) - pivot).rotate(-angle) + pivot
return [p0,p1,p2,p3]
Here is my code to check collison:
for i in vehicles:
i.render()
if i.getMask().intersects(car.getMask()):
death = True
I made a function to draw hitbox of car. But car and hitbox are different when angle of car isn't 0.
I am using shapely polygon to make rotated rects.
My english isn't very well, I tried to tell you as much as I could.
Upvotes: 1
Views: 99
Reputation: 210968
The image is rotated around it's center. You'll also need to rotate the rectangle around its center Therefore, the pivot point needs to be the center of the rectangle, not its top left point:
pivot = math.Vector2(irect[0],irect[1])
pivot = math.Vector2(irect.center)
calculate
function:
def calculate(irect,angle):
pivot = math.Vector2(irect.center)
p0 = (math.Vector2(irect.topleft) - pivot).rotate(-angle) + pivot
p1= (math.Vector2(irect.topright) - pivot).rotate(-angle) + pivot
p2 = (math.Vector2(irect.bottomright) - pivot).rotate(-angle) + pivot
p3 = (math.Vector2(irect.bottomleft) - pivot).rotate(-angle) + pivot
return [p0,p1,p2,p3]
Upvotes: 2