根据速度和方向更新位置

时间:2014-03-28 21:50:35

标签: python simulate

我已经完成了一个在线课程的pset,我们创建了随机移动网格清洁瓷砖的随机机器人。 我想创建一个机器人,按顺序清理每个瓷砖,并在我将速度设置为1.0时实现了这一点。

然而,当我将速度提高1时,机器人移动两个位置而不是一个位置,增加了与每次增加直接相关的移动。

以下是计算新职位的课程:

class Pos(object):
    """
    A Position represents a location in a two-dimensional room.
    """

    def __init__(self, x, y):
        """
        Initializes a position with coordinates (x, y).
        """
        self.x = x
        self.y = y

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def getNewPos(self, angle, speed):
        """
        Computes and returns the new Position after a single clock-tick has
        passed, with this object as the current position, and with the
        specified angle and speed.

        Does NOT test whether the returned position fits inside the room.

        angle: number representing angle in degrees, 0 <= angle < 360
        speed: positive float representing speed

        Returns: a Po sobject representing the new position.
        """
        old_x, old_y = self.getX(), self.getY()
        angle = float(angle)
        # Compute the change in position
        delta_y = speed * math.cos(math.radians(angle))
        delta_x = speed * math.sin(math.radians(angle))
        # Add that to the existing position
        new_x = old_x + delta_x
        new_y = old_y + delta_y
        return Position(new_x, new_y)

    def __str__(self):
        return "(%0.2f, %0.2f)" % (self.x, self.y)

机器人移动的速度和数量之间的关系是什么,我认为提高速度会增加他移动的速度,并且仍然考虑越过每个位置,但显然这是不正确的。

有人可以确切地解释计算是如何工作的,我已经很长时间没有使用过sin,cos等,这可以改变以实现我需要或者我需要的东西吗?

1 个答案:

答案 0 :(得分:1)

您的代码假定时间差值在每次调用时都是相同的(即每次调用 getNewPos 方法时,它都假设已经过了相同的时间量。比如说1秒)

因此,当速度为 1个单位/秒时,则每次通话时您的位置将改变 1个单位。但是,如果您将速度设置为 2个单位/秒,则每次调用时位置将被 2个单位更改,从而跳过其他所有位置。