繁体   English   中英

如何让我的播放器在浮动平台上运行?

[英]How do I make my player run on a floating platform?

我正在努力让我的播放器在从屏幕右侧到左侧水平悬停的浮动平台上运行。 为了解决这个问题,我正在考虑获取一个有效(x,y)坐标列表,如果我的播放器在平台上,它可以在这些坐标上运行。 这是它的代码 -

def vertical_collision(self):
    import playground
    can_jump = True
    keys = pygame.key.get_pressed()
    for platform in playground.platform_group:

        if self.rect.colliderect(platform.rect) and can_jump and self.image == self.player_jump:
            # if player stands on one of the terrains
            if self.rect.bottom >= platform.rect.top:
                # allows player to stand on the platform
                self.rect.bottom = platform.rect.top

                # player's x cor is changed according to platform's x cor
                where_to_run = [range(platform.rect.topleft, platform.rect.topright)]
                while self.rect.bottom in where_to_run:
                    self.rect.top = where_to_run

                if keys[pygame.K_w] or keys[pygame.K_UP]:
                    can_jump = False
                else:
                    can_jump = True

(此问题在评论下方的编码, # player's x cor is changed according to platform's x cor 。)

我的游戏从上面的代码中崩溃,我从堆栈跟踪中得到这个错误 -

Traceback (most recent call last):
  File "/Users/xyz/Documents/Extracurricular/Side Projects/pyGameTutorial/playground.py", line 69, in <module>
    player.update()  #
  File "/Users/xyz/Documents/Extracurricular/Side Projects/pyGameTutorial/Player.py", line 140, in update
    self.vertical_collision()
  File "/Users/xyz/Documents/Extracurricular/Side Projects/pyGameTutorial/Player.py", line 78, in vertical_collision
    import playground
  File "/Users/xyz/Documents/Extracurricular/Side Projects/pyGameTutorial/playground.py", line 69, in <module>
    player.update()  #
  File "/Users/xyz/Documents/Extracurricular/Side Projects/pyGameTutorial/Player.py", line 140, in update
    self.vertical_collision()
  File "/Users/xyz/Documents/Extracurricular/Side Projects/pyGameTutorial/Player.py", line 90, in vertical_collision
    where_to_run = [range(platform.rect.topleft, platform.rect.topright)]
TypeError: 'tuple' object cannot be interpreted as an integer

我不知道如何解决这个问题。 有人可以建议一种新方法或纠正我的错误,以便我的玩家可以站在平台上吗?

问题似乎是您的坐标存储在(10,15)之类的元组中,以指示 x 坐标为 10 和 y 坐标为 15。但是, where_to_run应仅包含 x 坐标范围,因此您应该只给出第一个元素元组的[0] 此外,您需要遍历范围以获取类似[x for x in range()]的列表:

# contains the platform's x cors
where_to_run = [x for x in range(platform.rect.topleft[0], platform.rect.topright[0]+1)]

我不确定您在while循环中尝试做什么,但它似乎不正确。 self.rect.top = where_to_run试图将平台的所有 x 坐标分配给没有意义的玩家。 我相信您可以用您希望玩家在平台上执行的任何特定操作来替换该行。

# while player's x cor is on the plaform's x cor do whatever
while self.rect.bottom[0] in where_to_run:
    # do whatever you want on the platform

# coming outside the while loop means player is no longer on the platform

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM