所以我有这些敌人,他们应该像旧街机游戏《机器人战机》中的那样,对玩家施展拳脚。在
问题是,只有几个敌人会去追那个玩家,而其他的敌人只是站在周围,也许会有更多的敌人来追这个玩家。这是怎么回事?在
以下是移动敌人的代码:
class Beetle(pygame.sprite.Sprite):
'''class that builds up the player class'''
x_speed = 0
y_speed = 0
#Beetle construction stuff (images, goes here)
.
.
.
def speedChange(self,x,y):
self.x_speed += x
self.y_speed += y
def move_towards_player(self, player):
#contains the beetle to the screen
self.rect.clamp_ip(screen_rect)
# find normalized direction vector (dx, dy) between enemy and player
dx, dy = self.rect.x - player.rect.x, self.rect.y - player.rect.y
dist = math.hypot(dx, dy)
if dist == 0: #prevents a divide by zero erro
dist = 1
else:
dx, dy = dx / dist, dy / dist
# move along this normalized vector towards the player at current speed
self.rect.x += dx * self.x_speed
self.rect.y += dy * self.y_speed
while done == False:
while beetleCount < 10:
beetle = Beetle() #make a beetle
random1 = randint(0, width -1 ) #make random positions for the beetle
random2 = randint(0, height - 1)
beetle.rect.x = random1 #make new random nums
beetle.rect.y = random2
beetle_list.add(beetle) #add beetle to list
all_sprites_list.add(beetle)
beetleCount += 1 #increment count'''
for bug in beetle_list:
random1 = randint(-1, 1)
if random1 != 0:
random2 = randint(-1, 1)
else:
random2 = 0
bug.speedChange(random1, random2)
bug.move_towards_player(player)
以下是整个代码,供参考:
^{pr2}$
但是x\u速度和y\u速度是随机的-1,0,或1,对吗?然后它会向一个随机的方向移动。。。也许你的意思是值1比值-1更有可能。在
我有一个类似的问题,我最终解决了分离目标速度从目标方向实施一个战略模式,让我根据需要交换敌人的行为。在
例如,让
Enemy
类在其self.update()
调用期间调用了一系列方法:因此
^{pr2}$self.move()
使用一个字符串来确定对象应该朝哪个方向移动以及如何应用它的速度。在通过这种方式,对象根据其
self.direction
值移动。在此之后,它将执行self.find_rect()
,它只在更改对象的x和y值后将其Rect设置为正确的值。在然后,seeker行为可以以多种方式应用于空的
def foo(self): pass
的包装器,或者使用types.MethodType()
或者仅仅作为主循环中的控制器,不管你喜欢什么,它只更新Enemy
对象的self.direction
值。在这是一种大量的代码和一些数学可能是多余的(深夜编码可以做到这一点,呵呵),但它基本上是检查“目标”(x,y)是否比它的速度要远,如果是的话,设置
self.direction
到哪个字符串。在我的意思是很明显它不一定是一个字符串来确定
self.direction
,它可以是任何你想要的系统,但是我认为将方向与运动分开是有帮助的。如果没有其他方法,则可以通过确保obj.move()
具有一致的实现来避免代码中的某些重复。而且它还避免了我在人们的代码中看到的很多丑陋的obj.speed *= -1
来表示某些东西正在朝另一个方向移动。也许我很奇怪,但我不认为这是正确的价值观改变;当我下班开车回家时,我没有开-35英里每小时。。。在相关问题 更多 >
编程相关推荐