pygame问题:sprite在树上运行

时间:2014-07-31 21:47:58

标签: python class events pygame sprite

我正在制作一款游戏,你可以在这里探索地形,随意随意电脑生成。作为精灵的玩家应该只在草地上跑,而且它不应该碰到树。换句话说,玩家只能在草地上奔跑。

然而,尽管经过数小时的调试,玩家仍然可以在树上跑步,这很烦人。

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': ...事应该有效,但事实并非如此。为什么? 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

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

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

逐步阅读循环并试一试:

e.g。

 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)

依旧等等。从这个希望你可以看到它 - 工作,只是没有你想象的那样,我可以挖掘关于计算机总是正确的东西

<强>解决方案:

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