【问题标题】:pygame issue: sprite running over treespygame问题:精灵在树上跑
【发布时间】:2014-07-31 21:47:58
【问题描述】:

我正在创建一个游戏,您可以在其中探索地形,始终是随机的和计算机生成的。玩家是一个精灵,应该只能在草块上奔跑,而不能跑到树上。也就是说,玩家只能在草地上奔跑。

然而,尽管调试了几个小时,玩家仍然可以在树上运行,这很烦人。

import pygame, player # the module where the Player class is defined
import block # the module where the Block class is  defined
...
#setting varibles, player, ...
run = True
clock = pygame.time.Clock()
create_world() # create the map of the world

while run:
    clock.tick(30)
    hit = pygame.sprite.spritecollide(player, blocks, False)
    location = player.rect.centerx # defined to use as return spot in case of tree
    # player is player.Player instance, blocks is group of all the blocks
    # the block.Block class has an attribute called 'type'; grass = 'block'
    # tree = 'tree'
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run = False
        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_UP:
                speed = [-30, 0] # the varible to update player's location
                if hit[0].type == tree: # if hit tree
                    player.rect.centerx = location
                ...
        if e.type == pygame.KEYUP:
            reset_speed() # speed = [0, 0], to prevent constant movement

    player.update(speed) # update the player
    reset_speed() # not really useful
    render_world() # blit the world & player
pygame.quit()

if hit[0].type == 'tree': ... 应该有效,但它没有。为什么? 任何帮助表示赞赏。

【问题讨论】:

  • 你的树在草地上吗? :P 所以 hit[0] == 'grass' 和 hit[1] == 'tree' ? :P
  • 没有。我的树不在草地上。 render_world() 函数在树和草之间进行选择,所以这是不可能的。不过我会试试的。
  • @JulienPalard:没用。
  • Julien 的评论提出了一个问题,spritecollide 返回一个列表,并且您总是取第一个元素,您应该检查可能返回的任何其他元素,如果不是因为这个问题,那么可能是另一个未来!

标签: python class events pygame sprite


【解决方案1】:

因此,为了帮助自己,循环中的标准处理是先移动,然后处理碰撞,这样您就可以同时了解之前的位置和碰撞的位置。

因此,在您当前的循环中,玩家可能会撞到一棵树,但只是移动到相同的位置。

逐步阅读循环并尝试一下:

例如

 loop N:
  hit returns []
  location is set to (posN)
  speed is set
  player moves to (posN+1)
 loopN+1:
  hit returns [tree]
  location is set to (posN+1)
  speed is set
  player is reset to "location", but that is just (posN+1)
  player moves to (posN+2)

等等等等。从这里希望你能看到它正在工作,只是不像你预期的那样,我可以挖掘出关于计算机总是正确的老话

解决方案:

稍微改写一下,考虑先处理运动,再检查循环内的碰撞,这样会更容易理解。

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 2023-03-23
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2019-03-23
    • 2023-03-05
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多