我一直在尝试创建一个马里奥类型的2d侧滚动平台使用python和pygame模块。我使用了编程游戏中的教程来编写平台和玩家的代码,我只是想不出如何实现在特定的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发布于 2019-02-05 05:39:24
对于与玩家的冲突,我建议你这样做:
#in your gameloop
playerEnemyCollision = pygame.sprite.spritecollide(player, enemies, False)敌人需要是一个精灵群组。要创建一个精灵群组:
#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()在大多数情况下,改变精灵的位置以在你的“敌人类”之外正常移动并不是一个好主意。我希望我能帮助你回答你的问题。特维斯蒂奥斯
https://stackoverflow.com/questions/54511561
复制相似问题