使物体不断地朝着一个方向移动

2024-10-01 09:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Pygame中做实验,试图制作一个自上而下的射手,发现了一个关于角向一个点here移动的脚本,并将其用于子弹。我有一个问题,我怎样才能让子弹沿着计算的方向移动。我的数学还不是很好,但我了解这里的大部分情况:

speed = speed
distance = [t0 - psx, t1 - psy]
norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
direction = [distance[0] / norm, distance[1 ] / norm]
bullet_vector = [direction[0] * speed, direction[1] * speed]

它基于deltaY/deltaX的斜率公式。对吗? 有人知道怎么做吗?在

以下是完整的源代码供参考:

^{pr2}$

Tags: 脚本normhere情况数学方向pygamedistance
1条回答
网友
1楼 · 发布于 2024-10-01 09:22:48

你的更新正在改变每次更新的项目符号向量的值,。。你真正想要的是矢量只在发射的那一刻被计算出来,然后根据初始矢量更新位置。。。所以把orb改成:

class Orb(object):
    def __init__(self,posorg,posdest):
        self.posx=posorg[0]
        self.posy=posorg[1]
        self.targ=posdest
        self.posorg=posorg
        self.bullet_vector=Move(self.targ[0],self.targ[1],self.posx,self.posy,20)
    def update(self):
        self.posx += self.bullet_vector[0]
        self.posy += self.bullet_vector[1]
        pygame.draw.circle(screen, ((0,0,255)), (int(self.posx),int(self.posy)), 5)

这样,运动矢量在创建时只计算一次。在

不过,您还应该添加一个检查项,看看项目符号是否仍在屏幕上。如果它不是你应该删除它,以节省资源,当你有很多子弹在一个游戏。在

祝你好运!在

相关问题 更多 >