我正在创造一款玩家可以探索地形的游戏,总是随机的&计算机生成的。作为精灵的玩家应该只在草地上奔跑,而不应该跑到树上。换句话说,玩家只能在草地上奔跑。
然而,尽管调试了几个小时,玩家仍然可以在树上跑,这是非常烦人的。
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': ...
应该起作用,但它没有。为什么?
所以,为了帮助你自己,循环中的标准处理是先移动,然后处理碰撞,这样你就可以知道之前的位置和碰撞的位置。
在你的当前循环中,玩家可能会撞到一棵树,但只是移动到相同的位置。
一步一步地读取循环,然后试试:
。
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)
等等。从这里,希望你能看到它正在工作,只是不像你期望的那样,我可以挖出那句关于计算机总是正确的老话
解决方案:
稍微重写一下,考虑先处理移动,然后在循环中检查碰撞,这样会更容易理解。