【问题标题】:How can I rotate my hitbox with my rotating and moving car in pygame?如何在 pygame 中用我的旋转和移动汽车旋转我的碰撞箱?
【发布时间】:2020-07-18 23:19:42
【问题描述】:

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

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

我的车课:

            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

我的完整代码是here

【问题讨论】:

  • 你可以试试Masks 用于像素完美碰撞

标签: python python-3.x pygame


【解决方案1】:

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

你没有。您必须使用pygame.mask.Maskoverlap()。 可以通过pygame.mask.from_surface()pygame.Surface 创建蒙版,并包含有关不透明像素的信息。 overlap() 在 2 个相交的蒙版中找到 1 个不透明像素。

例如:

class Car:
    # [...]

    def draw(self):
        # [...]

        self.mask = pygame.mask.from_surface(rotated)
        self.mask_rect = new_rect
obstacle_mask = pygame.mask.from_surface(obstacle_surface)

offset_x = obstacle_rect.x - car1.mask_rect.x
offset_y = obstacle_rect.y - car1.mask_rect.y

if 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),那么您可以从 pygame.Rect (obstacle_rect) 对象生成完全不透明的 Mask :

obstacle_mask = pygame.mask.Mask(obstacle_rect.width, True)

【讨论】:

  • 请问障碍物表面是什么?
  • !?任何你想要的。任何其他pygame.Surface 对象。
  • 嗯,我试图将我的 car1.rect 放在障碍物表面,但我不知道为什么我收到错误我想是什么对象,但我也不知道如何处理障碍物_rect.x ??我要放car1.x吗?而另一辆 car1.y?
  • @HabibIsmail 否。您正在针对其他东西测试汽车。所以障碍物不可能是汽车。
  • 哦,所以我可以用我的其他对象 rect 测试它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
相关资源
最近更新 更多