【问题标题】:updating positions based on speed and direction根据速度和方向更新位置
【发布时间】:2014-03-28 21:50:34
【问题描述】:

我从在线课程中完成了一个 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 等,可以改变它来实现我需要的东西还是我需要一些非常不同的东西?

【问题讨论】:

    标签: python simulate


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我是否需要一种完全不同的方法,计算速度而不是它的工作原理,抱歉,如果我不是很清楚,我对此没有什么经验。
    • 在您的上下文中,您真正想要增加的是时间分辨率(即减少时间增量)。相反,增加速度会增加每次增量所跨越的距离
    • 我该怎么做,我真的对此一无所知
    • 哈哈,这不在您发布的 Pos 类中:) 您需要跟踪代码的其他部分以查看 Pos 的使用方式。查找何时调用 getNewPos
    • 哈哈,这可能是一个有趣的练习。 self.robot_position.getNewPosition(self.robot_direction, self.speed),这就是我计算新位置的方式,这有什么关系?我已根据上一个位置的位置将方向设置为左上右下。
    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多