我的代码会产生多个追逐我的播放器的敌人。相反,敌人只停留在一个地方。这只发生在我尝试将一个值输入到生成坐标的敌人产生函数时。下面是代码:
clock = pygame.time.Clock()
keepGoing = True
try:
while keepGoing:
clock.tick(60)
screen.fill(THECOLORS['red'])
pygame.draw.rect(screen,THECOLORS['green'],(x,y,50,50))
char()
spawn1=spawn(200,200)#start
spawn1.AIPrototype()#end
pygame.display.flip()
这是产生敌人的功能。这里有一个功能:
prefix = value.prefix; console.log(value.prefix);
我不知道编码中的错误在哪里,所以如果有人可以帮助我,那就太棒了。
答案 0 :(得分:1)
这是矢量的一个例子。为了获得敌人的速度,我计算了玩家的矢量,然后将其标准化并缩放4(最终速度)。
vel = (player.center - self.pos).normalize() * 4
然后,您只需将vel
个数字添加到pos
,并将rect.center
设置为更新后的pos矢量即可移动该对象。
要生成新的敌人,首先要创建一个应该保存敌人实例的列表,然后在敌人产生时只按append
个新实例(按f键生成它们)。您也可以使用pygame sprites和精灵组代替Enemy类和列表。
import sys
import pygame as pg
class Enemy:
def __init__(self, pos, color):
self.rect = pg.Rect(pos, (26, 45))
self.color = color
self.pos = pg.math.Vector2(pos)
def update(self, player):
vel = (player.center - self.pos).normalize() * 4
self.pos += vel
self.rect.center = self.pos
def draw(self, screen):
pg.draw.rect(screen, self.color, self.rect)
def main():
screen = pg.display.set_mode((640, 480))
bg_color = pg.Color('gray12')
player_color = pg.Color('dodgerblue1')
enemy_color = pg.Color('sienna1')
clock = pg.time.Clock()
player = pg.Rect((100, 300), (26, 50))
enemy_list = [Enemy((100, 300), enemy_color)]
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_f:
enemy_list.append(Enemy((400, 0), enemy_color))
keys = pg.key.get_pressed()
if keys[pg.K_a]:
player.x -= 5
elif keys[pg.K_d]:
player.x += 5
if keys[pg.K_w]:
player.y -= 5
elif keys[pg.K_s]:
player.y += 5
for enemy in enemy_list:
enemy.update(player)
screen.fill(bg_color)
pg.draw.rect(screen, player_color, player)
for enemy in enemy_list:
enemy.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()