根据速度和方向更新位置

0 投票
1 回答
1609 浏览
提问于 2025-04-18 00:22

我完成了一个在线课程的编程作业,我们创建了随机的机器人,让它们在一个网格上随机移动,清理地砖。我想做一个按顺序清理每块地砖的机器人,当我把速度设置为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)

速度和机器人移动的距离之间有什么关系呢?我原以为提高速度只是让它移动得更快,同时也能确保它经过每个位置,但显然这样想是不对的。

有人能详细解释一下这些计算是怎么回事吗?我很久没用过正弦、余弦等数学函数了,这个可以调整来实现我的需求吗,还是我需要完全不同的方法?

1 个回答

1

你的代码假设每次调用时的时间间隔都是一样的(也就是说,每次调用getNewPos方法时,假设经过的时间都是相同的,比如说1秒)。

所以,当速度设定为1单位/秒时,每次调用你的当前位置会变化1单位。但是,如果你把速度设置为2单位/秒,那么每次调用时位置就会变化2单位,这样就会跳过中间的每一个位置。

撰写回答