在pygame的2D滚动平台游戏中定位和添加敌人?

2024-09-28 21:54:00 发布

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

我一直在尝试使用python和pygame模块创建mario类型的2d侧滚平台。我使用了programarcadegames的教程来编写平台和玩家的代码,我只是不知道如何实现在特定的x和y坐标下生成的敌人,并将它们添加为可碰撞的精灵(即在一次命中中“杀死”玩家)?你知道吗

教程代码如下:

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

我试着为敌人的精灵创建一个基本类,让它前后移动,但定位是我的主要问题。你知道吗

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

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

Tags: 代码rectimageselfinitdef玩家教程
1条回答
网友
1楼 · 发布于 2024-09-28 21:54:00

对于与玩家的碰撞,我向你推荐如下:

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

“敌人”必须是精灵-组。到创建精灵组:

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

要创建新敌人并将其添加到组中,只需键入:

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

在大多数情况下,改变一个精灵在你的“敌人职业”之外正常移动的位置并不是一个好主意。 我希望我能帮助你回答你的问题。 扭转

相关问题 更多 >