如何使用变化时间和速度来停止对目标位置的过冲

时间:2018-12-13 20:38:23

标签: python pygame game-physics

我正在尝试在轨道上上下移动“火车”。轨道是具有x和y坐标的节点的列表。

火车上下移动,但有时会视距离和速度而定,以1个deltatime的步长使一个节点超调,并由于没有注册该节点而开始左右跳动(或根据方向上下跳动)达到了。

我试图建立一个阈值。如果在像素的阈值量以内达到节点,则将下一个节点作为目标。这有帮助,但当然会不断发生,具体取决于距离和速度:

if dist <= 5:
        self.currentGoalNode += self.iterateBy

我尝试分别计算每毫秒的旅行距离,而不是时间间隔,并检查每个步骤中是否都达到了目标,但是无法正常工作,我停止尝试,因为它似乎导致了很多不必要的代码和计算。

是否有一种简单的方法可以解决此问题,或者我处于正确的“轨道”上,我是否需要使用额外的代码?

我的整个代码:

self.iterateBy = 1
self.floatPosition = self.rect.center

def move (self, dt):

    # calculate distance
    dist = math.hypot(self.path[self.currentGoalNode].x - self.rect.centerx,
                      self.path[self.currentGoalNode].y - self.rect.centery)

    # check if going up or down on path
    if self.currentGoalNode +1 >= self.totalNodes or self.currentGoalNode <= 0:
            self.iterateBy *= -1

    # attempt to eradicate the 'jumping' by making a treshold
    if dist <= 5:
        self.currentGoalNode += self.iterateBy

    diffx, diffy = (self.route[self.currentGoalNode][0] - self.rect.center[0],
                    self.route[self.currentGoalNode][1] - self.rect.center[1])

    angle = math.atan2(diffx, diffy)
    x = (math.sin(angle) * self.velocity) * dt
    y = (math.cos(angle) * self.velocity) * dt

    # keeping track of the position in floats
    self.floatPosition= tuple(map(sum, zip(self.floatPosition, (x,y))))

    # moving the rect and converting to ints
    self.rect.center = self.floatPosition

1 个答案:

答案 0 :(得分:1)

如果距离目标只有1个增量(1dist <=阈值),则不要添加iterator。相反,只需将位置设置为目标位置即可。