Collisions still aren't getting detected in pygame

萝らか妹 提交于 2021-02-02 09:33:40

问题


I've tried making some of the changes from the other question I had asked, here's the link: Collisions aren't being detected in pygame

But anyway, I'm trying to make an asteroids style game, where the asteroids can be destroyed when shot by the player and the ship will be destroyed when hit by an asteroid. The problem is, my collisions aren't being detected at all and they're harmlessly passing through each other.

Since people couldn't run my code last time, here are the sprites I'm using:

ship_on =

ship_off =

space =

bullet =

asteroid =

and here's my code:

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()

Hopefully, having sprites can help.


回答1:


The operations spritecollide and groupcollide use the .rect attribute of a Sprite object to detect the collision.
Hence, when you change the position of a Sprite object (.x, .y), then you have to update the .rect attribute, too.

At the end of the method move of the class Ship:

class Ship:
    # [...]

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

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

And for the bullets and asteroids in the main application loop:

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()



来源:https://stackoverflow.com/questions/63465025/collisions-still-arent-getting-detected-in-pygame

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