【发布时间】:2014-04-19 17:28:48
【问题描述】:
基本上我试图让我的敌人角色在地图上随机移动。我已经实现了这一点,但是随机运动仅在它们撞到墙上时发生(使其看起来更自然)。有没有更好的方法来做到这一点?还是应该移动我的地图,让角色更频繁地撞墙?
def update(self, walls, player):
# Check if moving left / right caused a collision
self.rect.x += self.x_speed
walls_hit = pygame.sprite.spritecollide(self, walls, False)
for wall in walls_hit:
if self.x_speed > 0:
self.rect.right = wall.rect.left
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.x_speed = 0
self.y_speed = 3
else:
self.x_speed = 0
self.y_speed = -3
else:
self.rect.left = wall.rect.right
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.x_speed = 0
self.y_speed = 3
else:
self.x_speed = 0
self.y_speed = -3
# Check if moving up / down caused a collision
self.rect.y += self.y_speed
walls_hit = pygame.sprite.spritecollide(self, walls, False)
for wall in walls_hit:
if self.y_speed > 0:
self.rect.bottom = wall.rect.top
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.y_speed = 0
self.x_speed = 3
else:
self.y_speed = 0
self.x_speed = -3
else:
self.rect.top = wall.rect.bottom
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.y_speed = 0
self.x_speed = 3
else:
self.y_speed = 0
self.x_speed = -3
如果有帮助,下面的代码就是我的地图(1 的 = 墙壁,0 的 = 地板)
GRID = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
任何帮助将不胜感激!
【问题讨论】: