Pygame mask collision

旧街凉风 提交于 2020-05-09 06:34:13

问题


I'm trying to get proper collision detection with rotating surfaces in pygame. I decided to try using masks. It somewhat works, but it is not as precise as I'd liked/thought. I tried updating the mask at the end of the cycle to get a "fresh" hitbox for the next frame, but it didn't work as expected. What is my mistake?

import pygame
import random

WHITE = [255, 255, 255]
RED = [255, 0, 0]

pygame.init()

FPS = pygame.time.Clock()
fps = 6

winW = 1000
winH = 500
BGCOLOR = WHITE
win = pygame.display.set_mode((winW, winH))
win.fill(WHITE)
pygame.display.set_caption('')
pygame.display.set_icon(win)


class Box(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([w, h], pygame.SRCALPHA)
        self.image.fill(random_color())
        self.mask = pygame.mask.from_surface(self.image)
        self.rect = pygame.Rect(x, y, w, h)
        self.angle = 0

    def move(self):
        self.rect.center = pygame.mouse.get_pos()

    def draw(self):
        blits = self.rotate()
        win.blit(blits[0], blits[1])
        self.mask = pygame.mask.from_surface(blits[0])

    def rotate(self):
        self.angle += 3
        new_img = pygame.transform.rotate(self.image, self.angle)
        new_rect = new_img.get_rect(center=self.rect.center)
        return new_img, new_rect


def update_display():
    win.fill(BGCOLOR)
    player.draw()
    for p in platforms:
        p.draw()
    pygame.display.update()


def collision():
    return pygame.sprite.spritecollide(player, plat_collide, False, pygame.sprite.collide_mask)


def random_color():
    return [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]


player = Box(100, 400, 50, 50)

platforms = [Box(300, 400, 100, 50)]
plat_collide = pygame.sprite.Group(platforms)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    hits = collision()
    if hits:
        BGCOLOR = RED
    else:
        BGCOLOR = WHITE

    player.move()

    update_display()

    FPS.tick(fps)

pygame.quit()

回答1:


Your application works fine. But note, pygame.sprite.collide_mask() use the .rect and .mask attribute of the sprite object for the collision detection.
You have to update self.rect after rotating the image:

class Box(pygame.sprite.Sprite):
    # [...]

    def rotate(self):
        self.angle += 3
        new_img = pygame.transform.rotate(self.image, self.angle)
        new_rect = new_img.get_rect(center=self.rect.center)

        # update .rect attribute
        self.rect = new_rect # <------

        return new_img, new_rect



来源:https://stackoverflow.com/questions/60077813/pygame-mask-collision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!