pygame中仍然没有发现碰撞

如何解决pygame中仍然没有发现碰撞

我尝试从我提出的另一个问题中进行一些更改,这是链接: Collisions aren't being detected in pygame

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

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

ship_on =

enter image description here

ship_off =

enter image description here

space =

enter image description here

项目符号=

enter image description here

asteroid =

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)


# 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.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.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.y - (self.image_copy.get_height()) / 2))


class Projectiles(pygame.sprite.Sprite):

    def __init__(self,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,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))
    ship.move()
    redraw()

pygame.quit()

希望精灵有帮助。

解决方法

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

move的方法Ship的结尾:

class Ship:
    # [...]

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

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

对于主应用程序循环中的bulletsasteroids

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-