如何在PyGame中使用向量创建精灵碰撞?

2024-10-03 19:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

https://github.com/maartenww/100daysOfCode_projectOne/tree/StackOverflow (作为参考,这里是对我的代码的回购,带有错误代码的分支(因此其他人仍然可以阅读)

嗨,我正在创建一个平台,我遇到了一个问题,我试图使用pygame库使两个精灵之间的碰撞工作。在

class Game:

    def sprite_col(self, player_1, platform_list):
        sprites_hit = pygame.sprite.spritecollide(player_1, platform_list, False)

精灵的位置是用pygame向量计算出来的

^{pr2}$

但是,我不知道为什么顶部代码块不运行。 我在谷歌上搜索了我的问题,并看了这个视频,我用它作为参考 公司名称:

https://www.youtube.com/watch?v=pN9pBx5ln40&list=PLsk-HSGFjnaG-BwZkuAOcVwWldfCLu1pq&index=3(跳到8:40)

它给出了以下错误:

回溯(最近一次呼叫): 文件“C:/ScrewAround/100DaysOfCodeProject1/主.py“,第81行,英寸 主()

文件“C:/ScrewAround/100DaysOfCodeProject1/主.py“,第76行,主要内容 g、 运行(玩家1)

文件“C:/ScrewAround/100DaysOfCodeProject1/主.py“,第65行,运行中 自我更新游戏(玩家1)

文件“C:/ScrewAround/100DaysOfCodeProject1/主.py“,第58行,在更新游戏中 自我精神科(玩家1)

文件“C:/ScrewAround/100DaysOfCodeProject1/主.py“,第41行,在雪碧柱 精灵命中=pygame.sprite.sprite碰撞(玩家1,平台精灵,错误)

文件“C:\ScrewAround\100DaysOfCodeProject1\venv\lib\site packages\pygame\精灵.py,第1524行,在spritecollide中 精灵碰撞=sprite.rect.colliderect在

属性错误:'pygame.math.Vector2'object没有属性'colliderect'

如你所见,这是一个带有向量和colliderect的AttributeError。 但是我不知道这与我的代码有什么关系,因此 不知道错误指的是哪里。在


Tags: 文件代码pyhttpscom错误玩家平台
1条回答
网友
1楼 · 发布于 2024-10-03 19:26:18

在您的Player类中,您有以下函数:

def update_player(self):
    # Gravity
    self.player_vel.y += self.player_acc.y
    self.player_pos.y += self.player_vel.y + self.player_acc.y * .5
    # Acceleration
    self.rect = self.player_pos
    self.player_vel.x += self.player_acc.x
    self.player_pos.x += self.player_vel.x + self.player_acc.x * .5
    # Friction
    self.player_acc.x += (self.player_vel.x * -PLAYER_FRIC) / 1000
    if (self.player_vel.x > -.1) and (.1 > self.player_vel.x):
        self.player_acc.x = 0
        self.player_vel.x = 0
    elif(self.player_vel.x > 15) and (-15 > self.player_vel.x):
        self.player_vel.x = 15
        self.player_acc.x = 15

注意这条线

^{pr2}$

player_posVector2。所以,在这行之后,self.rect也将是Vector2。在

但是pygame库中处理Sprite的每个函数都期望Sprite有一个rect类型为Rect的字段。因此出现错误:spritecollide想要使用Rect.colliderect。在

您可以使用一个自定义的collide函数并在spritecollide中使用它,但是如果您去掉player_pos而只使用rect字段来存储精灵的位置,那就更好了。在

另一种方法是将Rect更改为存储在向量中的位置,就像您已经在__init__函数中所做的那样:

 self.rect.x = self.player_pos.x
 self.rect.y = self.player_pos.y

相关问题 更多 >