Pygame如何在点列表中移动?

1 投票
1 回答
804 浏览
提问于 2025-04-18 02:35

我正在尝试制作一个塔防游戏,但我需要让敌人沿着一条路径移动。我以为我已经搞定了,但当我去测试我的代码时,它只在有时候有效。

有时候敌人会到达它应该去的地方,有时候又不会。这个移动是基于一系列点,这些点构成了路径。我让敌人依次经过这些点,当它到达一个点时,就会去下一个点。

我尝试了很多不同的方法来检查敌人是否接触到那个点,但没有一个方法能一直有效。目前代码中的方法效果最好,但也不是每次都能成功。

except ZeroDivisionError:
    bullet_vector=''
if bullet_vector==(0,0):
    bullet_vector=''

从我能看出来的,我只需要找到一个更好的方法来判断物体是否到达了它应该改变方向的点。以下是代码:

import pygame,math
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((640,480))
run=True
clock=pygame.time.Clock()
def Move(t0,t1,psx,psy,speed):
    global mx
    global my

    speed = speed

    distance = [t0 - psx, t1 - psy]
    norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
    try:
        direction = [distance[0] / norm, distance[1 ] / norm]
        bullet_vector = [int(direction[0] * speed), int(direction[1] * speed)]
    except ZeroDivisionError:
        bullet_vector=''
    if bullet_vector==(0,0):
        bullet_vector=''
    return bullet_vector

class AI(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.path=[(144,114),(280,114),(280,301),(74,300),(74,400)]
    def update(self):
        self.move_vector=Move((self.path[0])[0],(self.path[0])[1],self.x,self.y,1)
        if self.move_vector != '':
            self.x += self.move_vector[0]
            self.y += self.move_vector[1]
        else:
            self.path=self.path[1:]
        pygame.draw.circle(screen,((255,0,0)),(self.x,self.y),3,0)
enemies=[AI(-5,114)]
while run:
    screen.fill((0,200,0))
    for e in enemies:
        e.update()
    for e in pygame.event.get():
        if e.type==QUIT:
            run=False
    clock.tick(99)
    pygame.display.flip()

如果有人能找出我哪里出错了,我将非常感激。

1 个回答

1

我自己找到了答案,不过它只支持四个方向的移动(这正是我需要的)。而且它还可以调节速度!如果有人需要的话,这里有代码:

import pygame,math
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((640,480))
run=True
themap=pygame.image.load('map1.png')
clock=pygame.time.Clock()

class AI(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.path=[(144,114),(280,114),(280,300),(100,302)]
    def update(self):
        speed=2
        if self.x<(self.path[0])[0]:
            self.x+=speed
        if self.x>(self.path[0])[0]:
            self.x-=speed
        if self.y<(self.path[0])[1]:
            self.y+=speed
        if self.y>(self.path[0])[1]:
            self.y-=speed
        z=(self.x-(self.path[0])[0],self.y-(self.path[0])[1])
        if (z[0]/-speed,z[1]/-speed)==(0,0):
            self.path=self.path[1:]
        pygame.draw.circle(screen,((255,0,0)),(self.x,self.y),3,0)
enemies=[AI(-5,114)]
while run:
    screen.blit(themap,(0,0))
    for e in enemies:
        e.update()
    for e in pygame.event.get():
        if e.type==QUIT:
            run=False
    clock.tick(60)
    pygame.display.flip()

撰写回答