问题描述
我有关于旋转矩形碰撞的问题。
这是我的汽车课:
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)
这是我的“计算”功能:
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]
这是我检查碰撞的代码:
for i in vehicles:
i.render()
if i.getMask().intersects(car.getMask()):
death = True
我做了一个函数来绘制汽车的hitBox。但是当car的角度不为0时,car和hitBox是不同的。
我正在使用匀称的多边形来制作旋转的矩形。
我的英语不是很好,我尽量告诉你。
解决方法
图像围绕其中心旋转。您还需要围绕其中心旋转矩形因此,枢轴点需要是矩形的中心,而不是其左上角:
import random
cards = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
suits = ["Diamonds","Hearts","Spades","Clubs"]
print(random.choice(cards) + " of ") print(random.choice(suits))
pivot = math.Vector2(irect[0],irect[1])
pivot = math.Vector2(irect.center)
函数:
calculate