python - 在 pygame 2d 滚动平台游戏中定位和添加敌人?

标签 python pygame

我一直在尝试使用 python 和 pygame 模块创建马里奥类型的 2d 横向滚动平台游戏。我使用了 programarcadegames 的教程来编写平台和播放器的代码,我只是想不出如何实现在特定 x 和 y 坐标处生成的敌人并将它们添加为可碰撞的 Sprite (即“杀死”玩家)命中)?

教程代码如下:

http://programarcadegames.com/python_examples/show_file.php?file=platform_moving.py

我尝试为敌人 Sprite 创建基本类并使其前后移动,但定位它是我的主要问题。

这是我的代码:(当关卡滚动时,敌人确实有点小故障)

class Enemy(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()

        width = 30
        height = 30
        self.image = pygame.Surface([width, height])
        self.image.fill(BLUE)

        # Set a reference to the image rect.
        self.rect = self.image.get_rect()

        # Set speed vector of player
        self.change_x = random.randint(3, 4)
        self.change_y = 0

    def update(self):

        self.rect.centerx += self.change_x
        if self.rect.right <= 0 or self.rect.left >= 100:
            self.change_x *= -1

最佳答案

对于与播放器的碰撞,我推荐你这样:

#in your gameloop
playerEnemyCollision = pygame.sprite.spritecollide(player, enemies, False)

“敌人”需要是 Sprite 组。要创建 Sprite 组:

#outside your gameloop
enemies = pygame.sprite.Group()

要创建一个新的 Enemy 并将其添加到组中,只需输入:

#outside your gameloop
en = Enemy()
en.rect.x = XX #set your Enemies x-Position
en.rect.y = YY #set your Enemies y-Position
en.add(enemies) #adds the enemy "en" to the sprite-group "enemies"

现在您可以检查碰撞:

#in your gameloop
if playerEnemyCollision:
    #your "kill-player-code" goes her
    #Example:
    player.kill()

在大多数情况下,更改 Sprite 的位置以使其在您的“敌对等级”之外正常移动并不是一个好主意。 我希望我能帮助你解决你的问题。 扭曲

关于python - 在 pygame 2d 滚动平台游戏中定位和添加敌人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511561/

相关文章:

python - Pygame 复制图形

Python 不允许在三元中有多个 return() 语句;在美学上也令人愉悦的可能替代方案?

python - Pygame:奇怪的 blitting 错误

python - 使用 Python 压缩 PDF

python - 如何执行我的脚本并在 PYQT5 的 GUI 中打印它?

python - 使图像背景透明的问题: pygame

python - Pygame碰撞问题

python - 进程结束,退出代码为 -1073741515 (0xC0000135)

python - 三重奏 : multiple tasks reading from the same fd

python - uWSGI cron-like 接口(interface),基于信号的定时器