我正在创建一个平铺游戏,其中有NPC的。我可以成功地创建一个NPC,但当我绘制多个NPC时,它们在代码运行几秒钟后共享同一位置。我创建了这个示例来演示我的意思
import pygame, random, math
screen = pygame.display.set_mode((800,600))
NPCP = {'Bob' : (2,6), 'John' : (4,4)} # 25, 19 max width and height
pygame.time.set_timer(pygame.USEREVENT, (100))
sMove = True
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.USEREVENT:
sMove = True
screen.fill((0,0,255))
for name in NPCP:
x,y = NPCP.get(name)
pygame.draw.rect(screen, (255,0,0), (x*32,y*32,50,50))
if sMove == True:
move = random.randint(1,4)
sMove = False
if move == 1:
if math.floor(y) > 2:
y -= 2
if move == 2:
if math.floor(y) < 17:
y += 2
if move == 3:
if math.floor(x) < 23:
x += 2
if move == 4:
if math.floor(x) > 2:
x -= 2
print(x,y)
NPCP[name] = (x,y)
pygame.display.flip()
在这种情况下,我使用字典来创建这些NPC或矩形。我用一个计时器和一个从1到4的随机数来移动它们,以选择要做的移动。我使用for循环为每个NPC运行。我想知道如何让这些矩形不以相同的方式移动,并且位置不会最终改变到相同的位置,并且彼此移动不一样。我还想让它用字典来做
如果要单独移动对象,则必须为每个对象生成一个随机方向
在您的代码中,只为所有对象生成on direction,因为
sMove
是在生成第一个对象的方向之后立即设置的False
。此方向用于所有对象。此外,移动方向(
move
)永远不会重置为0。这会导致最后一个随机方向应用于所有后续帧,直到方向再次更改重置
sMove
重置move
在循环和之后,要解决此问题:相关问题 更多 >
编程相关推荐