python - pygame 中仍然没有检测到碰撞

标签 python pygame

我尝试对我提出的其他问题进行一些更改,链接如下: Collisions aren't being detected in pygame

但无论如何,我正在尝试制作一款小行星风格的游戏,其中小行星可以在被玩家射击时被摧毁,而飞船在被小行星击中时也会被摧毁。问题是,我的碰撞根本没有被检测到,它们只是无害地相互穿过。

由于上次人们无法运行我的代码,以下是我正在使用的 Sprite :

ship_on = enter image description here

ship_off = enter image description here

空格= enter image description here

项目符号 = enter image description here

小行星= enter image description here

这是我的代码:

import pygame
from math import sin, cos, pi

from random import randint

scr_width = 800
scr_height = 600
window = pygame.display.set_mode((scr_width, scr_height))
pygame.display.set_caption("Asteroids")
clock = pygame.time.Clock()
space_img = pygame.image.load("sprites/space.jpg")
red = (255, 0, 0)


# todo object collisions
# todo shooting at larger intervals
# todo score system
# todo asteroid division

class Ship:
    def __init__(self, x, y):

        self.x = x
        self.y = y
        self.width = 0
        self.vel = 0
        self.vel_max = 12
        self.angle = 0
        self.image = pygame.image.load("sprites/ship_off.png")
        self.image_copy = pygame.transform.rotate(self.image, self.angle)
        self.mask = pygame.mask.from_surface(self.image_copy)
        self.rect = pygame.Rect(self.x - (self.image_copy.get_width()) / 2,
                                self.y - (self.image_copy.get_height()) / 2,
                                self.image_copy.get_width(), self.image_copy.get_height())

    def draw(self):
        self.image = pygame.image.load("sprites/ship_off.png")
        self.image_copy = pygame.transform.rotate(self.image, self.angle)

        window.blit(self.image_copy,
                    (self.x - (self.image_copy.get_width()) / 2, self.y - (self.image_copy.get_height()) / 2))
        keys = pygame.key.get_pressed()

        if keys[pygame.K_w]:
            self.image = pygame.image.load("sprites/ship_on.png")
            self.image_copy = pygame.transform.rotate(self.image, self.angle)
            window.blit(self.image_copy,
                        (self.x - (self.image_copy.get_width()) / 2, self.y - (self.image_copy.get_height()) / 2))

    def move(self):
        keys = pygame.key.get_pressed()
        # todo acceleration and thrust mechanics
        if keys[pygame.K_w]:
            self.vel = min(self.vel + 1, self.vel_max)
        elif self.vel > 0:
            self.vel = self.vel - 0.4
        if keys[pygame.K_a]:
            self.angle += 7

        if keys[pygame.K_d]:
            self.angle -= 7

        self.x += self.vel * cos(self.angle * (pi / 180) + (90 * pi / 180))
        self.y -= self.vel * sin(self.angle * (pi / 180) + 90 * (pi / 180))
        # So that if it leaves one side it comes from the other
        if self.y < 0:
            self.y = (self.y - self.vel) % 600

        elif self.y > 600:
            self.y = (self.y + self.vel) % 600

        elif self.x < 0:
            self.x = (self.x - self.vel) % 800

        elif self.x > 800:
            self.x = (self.x + self.vel) % 800


class Asteroid(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()

        y_values = [1, 599]
        self.x = randint(0, 800)
        self.y = y_values[randint(0, 1)]
        # If object spawns from the top, it moves down instead of moving up and de-spawning immediately
        if self.y == y_values[0]:
            self.neg = -1
        else:
            self.neg = 1
        self.speed = randint(5, 10)
        self.ang = randint(0, 90) * (pi / 180)
        self.ang_change = randint(1, 5)

        self.asteroid_angle = randint(0, 80)
        self.image = pygame.image.load("sprites/asteroid.png")
        self.image_copy = pygame.transform.rotate(self.image, self.ang)
        self.mask = pygame.mask.from_surface(self.image_copy)
        self.rect = pygame.Rect(self.x - (self.image_copy.get_width()) / 2,
                                self.y - (self.image_copy.get_height()) / 2,
                                self.image_copy.get_width(), self.image_copy.get_height())

    def generate(self):
        self.ang += self.ang_change
        self.image = pygame.image.load("sprites/asteroid.png")
        self.image_copy = pygame.transform.rotate(self.image, self.ang)

        window.blit(self.image_copy,
                    (self.x - (self.image_copy.get_width()) / 2, self.y - (self.image_copy.get_height()) / 2))


class Projectiles(pygame.sprite.Sprite):

    def __init__(self, x, y, angle):
        super().__init__()
        self.x = x
        self.y = y
        self.angle = angle
        self.vel = 20
        self.image = pygame.image.load("sprites/bullet.png")
        self.mask = pygame.mask.from_surface(self.image)
        self.rect = self.rect = pygame.Rect(self.x - (self.image.get_width()) / 2,
                                            self.y - (self.image.get_height()) / 2, 5, 5)

    def draw(self):
        window.blit(self.image, (self.x - 2, self.y))


def redraw():
    window.blit(space_img, (0, 0))
    ship.draw()
    for asteroid in asteroids:
        asteroid.generate()
    for bullet in bullets:
        bullet.draw()

    pygame.display.update()


def collisions():
    pygame.sprite.spritecollide(ship, asteroids, True, pygame.sprite.collide_mask)
    pygame.sprite.groupcollide(asteroids, bullets, True, True, pygame.sprite.collide_mask)


# main loop
run = True
ship = Ship(400, 300)
next_fire = pygame.time.get_ticks() + 400
asteroids = pygame.sprite.Group()
bullets = pygame.sprite.Group()
while run:
    clock.tick(60)
    keys = pygame.key.get_pressed()
    pygame.time.delay(35)
    collisions()

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

    if keys[pygame.K_SPACE]:
        if len(bullets) < 11 and pygame.time.get_ticks() >= next_fire:
            bullets.add(
                Projectiles(round(ship.x + ship.width - 6.5 // 2), round(ship.y + ship.width - 6.5 // 2), ship.angle))
            next_fire = pygame.time.get_ticks() + 400

    for bullet in bullets:
        if 800 > bullet.x > 0 and 600 > bullet.y > 0:
            bullet.x += bullet.vel * cos(bullet.angle * (pi / 180) + 90 * (pi / 180))
            bullet.y -= bullet.vel * sin(bullet.angle * (pi / 180) + 90 * (pi / 180))
        else:
            bullet.kill()
    # To limit the number of asteroids on screen
    if len(asteroids) < 5:
        asteroids.add(Asteroid())

    for asteroid in asteroids:
        if 800 > asteroid.x > 0 and 600 > asteroid.y > 0:
            asteroid.x += asteroid.speed * cos(asteroid.asteroid_angle * (pi / 180) + 90 * (pi / 180))
            asteroid.y -= asteroid.speed * sin(asteroid.asteroid_angle * (pi / 180) + 90 * (pi / 180)) * asteroid.neg
            if asteroid.x < 0:
                asteroid.x = (asteroid.x - asteroid.speed) % 800

            elif asteroid.x > 800:
                asteroid.x = (asteroid.x + asteroid.speed) % 800

        else:
            asteroid.kill()

    window.fill((0, 0, 0))
    ship.move()
    redraw()

pygame.quit()

希望 Sprite 能有所帮助。

最佳答案

操作spritecollidegroupcollide使用 Sprite.rect 属性检测碰撞的对象。
因此,当您更改 Sprite 对象的位置(.x.y)时,您必须更新 .rect 属性,也是。

在类Ship的方法move的末尾:

class Ship:
    # [...]

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

        self.rect.center = (self.x, self.y) # <---- ADD

对于主应用程序循环中的子弹小行星:

while run:
    # [...]

    for bullet in bullets:
        if 800 > bullet.x > 0 and 600 > bullet.y > 0:
            bullet.x += bullet.vel * cos(bullet.angle * (pi / 180) + 90 * (pi / 180))
            bullet.y -= bullet.vel * sin(bullet.angle * (pi / 180) + 90 * (pi / 180))

            bullet.rect.center = (bullet.x, bullet.y) # <---- ADD

        else:
            bullet.kill()
    # To limit the number of asteroids on screen
    if len(asteroids) < 5:
        asteroids.add(Asteroid())

    for asteroid in asteroids:
        if 800 > asteroid.x > 0 and 600 > asteroid.y > 0:
            asteroid.x += asteroid.speed * cos(asteroid.asteroid_angle * (pi / 180) + 90 * (pi / 180))
            asteroid.y -= asteroid.speed * sin(asteroid.asteroid_angle * (pi / 180) + 90 * (pi / 180)) * asteroid.neg
            if asteroid.x < 0:
                asteroid.x = (asteroid.x - asteroid.speed) % 800

            elif asteroid.x > 800:
                asteroid.x = (asteroid.x + asteroid.speed) % 800
            
            asteroid.rect.center = (asteroid.x, asteroid.y) # <---- ADD

        else:
            asteroid.kill()

关于python - pygame 中仍然没有检测到碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63465025/

相关文章:

python - 在/和\之间查找子字符串

当在屏幕中添加外星人时,Python Pygame 船移动缓慢

python - 元组出了什么问题

python - 减少文本文件大小的编程技术

python - 如何使用 category_encoder 包获取二进制编码的原始值

python - 将这样的 URI 'foo://user:pass@host:port' 解析为适当变量的 pythonic 方法是什么?

python - 从 ndarrys 的 ndarray 中删除元素

python - PyGame 角色离开屏幕

python - 我一直在尝试在 PyGame 中制作游戏,但碰撞检测器不起作用

python - PyGame:每次移动鼠标时计时器都会重置