如何在 pygame 中用我旋转和移动的汽车旋转我的碰撞箱?

我正在尝试将我的汽车精灵与另一个矩形碰撞,现在我正在使用矩形碰撞和我的汽车碰撞视频,但每次我旋转碰撞箱时它都会移动到其他地方。


有没有办法让我的汽车精灵与那个碰撞箱发生碰撞,而不是使用汽车碰撞箱?


我的汽车等级:


            class Car:

              def __init__(self, x, y, height, width, color):

              self.x = x - width / 2

            self.y = y - height / 2

            self.height = height

            self.width = width

            self.color = color

            self.rect = pygame.Rect(x, y, height, width)

            self.surface = pygame.Surface((height, width), pygame.SRCALPHA)

            self.surface.blit(img, (0, 0))

            self.angle = 250

            self.speed = 0# 2


            self.hitbox = (self.x + 90, self.y + 620, 370, 63)# CARS HITBOX

            pygame.draw.rect(window, (255, 0, 0), self.hitbox, 2)


            def draw(self): #3

            self.rect.topleft = (int(self.x), int(self.y))

            rotated = pygame.transform.rotate(self.surface, self.angle)

            surface_rect = self.surface.get_rect(topleft = self.rect.topleft)

            new_rect = rotated.get_rect(center = surface_rect.center)

            window.blit(rotated, new_rect.topleft)

            self.hitbox = (self.x, self.y, 70, 40)# CARS HITBOX BLITTING AT car x, y

            pygame.draw.rect(window, (255, 0, 0), self.hitbox, 2)# draw the car hitbox


            white = (255, 255, 255)

            car1 = Car(100, 630, 73, 73, white)# 4

我的完整代码在这里


温温酱
浏览 97回答 1
1回答

白猪掌柜的

如何在 pygame 中用我旋转和移动的汽车旋转我的碰撞箱?你不知道。你必须使用pygame.mask.Mask和overlap()。掩码可以从创建pygame.Surface并pygame.mask.from_surface()包含有关不透明像素的信息。overlap()在相交的 2 个蒙版中找到 1 个不透明像素。例如:class Car:    # [...]    def draw(self):        # [...]        self.mask = pygame.mask.from_surface(rotated)        self.mask_rect = new_rectobstacle_mask = pygame.mask.from_surface(obstacle_surface)offset_x = obstacle_rect.x - car1.mask_rect.xoffset_y = obstacle_rect.y - car1.mask_rect.yif car1.mask.overlap(obstacle_mask, (offset_x, offset_y)):    print("hit")请注意, 的偏移量参数overlap()是从该掩码到另一个掩码(到第一个参数)的偏移量。它是参数中从掩码到另一个掩码的向量。如果self的位置是 ( x1 , y1 ) 而other的位置是 ( x2 , y2 ) 那么偏移量是 ( x2 - x1 , y2 - y1 )。如果障碍物只是一个矩形并且您没有 Surface ( ),那么您可以从( ) 对象obstacle_surface生成一个完全不透明的 Mask :pygame.Rectobstacle_rectobstacle_mask = pygame.mask.Mask(obstacle_rect.width, True)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python