python找到两个3D点之间的矢量方向

时间:2014-11-08 18:42:21

标签: python

我正在尝试计算从我的宇宙飞船游戏中导航的点(x,y,z)开始到结束点(a,b,c)的3D矢量的方向,但是我无法找到有用的东西。到目前为止,我已经尝试使用两个圆圈,一个用于计算x和y,另一个用于z,用于计算出来,只有两个向量的距离非常相似时代码才有效。

以下是我正在使用的内容:

def setcourse(self, destination):
    x1, y1, z1 = self.coords
    x2, y2, z2 = destination

    dx = x2 - x1
    dy = y2 - y1
    dz = z2 - z1

    self.heading = math.atan2(dy, dx)
    self.heading2 = math.atan2(dz, dy)

    self.distance = int(math.sqrt((dx) ** 2 + (dy) ** 2))
    self.distance2 = int(math.sqrt((dy) ** 2 + (dz) ** 2))

def move(self):
    if self.distance > 0 and self.distance2 > 0:
        if self.atwarp == True:
            x, y, z = self.coords
            x += math.cos(self.heading) * self.speed
            y += math.sin(self.heading) * self.speed
            z += math.sin(self.heading2) * self.speed

            self.coords = (x, y, z)
            print(str(self.coords))
            self.distance -= self.speed
            self.distance2 -= self.speed

    elif self.distance <= 0 and self.distance2 <= 0 and self.atwarp == True:
        self.atwarp = False
        self.speed = 0
        print("Reached Destination")

    else:
        self.atwarp = False

我不确定这是一个数学错误有多少,编程是多少,但z结束了,我不知道如何修复它。无论我做什么,如果它的输入与其他输入略有不同,则z总是关闭。

以下是从(0,0,0)开始的示例。我试图让输出与输入相似但是与输入相同。

输入:(100,200,-200)

Vector1以弧度为单位:1.1071487177940904 Vector2标题:2.356194490192345

Vector1距离:223 Vector2距离:282

输出:(99.7286317964909,199.4572635929818,157.68481220460077) x和y很好,但z关闭了。

输入:( - 235,634,-21)

Vector1以弧度为单位:1.9257588105240444 Vector2标题:1.6039072496758664

Vector1距离:676 Vector2距离:634

输出:( - 220.3499891866359,594.4761410396925,633.6524941214135) z关闭。

1 个答案:

答案 0 :(得分:1)

运动的方向是你计算的三重奏dx,dy,dz。这个向量不纯: 它包含距离和方向。如果你只想要方向,你必须规范化 这个:

距离是sqrt(dx ^ 2 + dy ^ 2 + dz ^ 2)。

对于标准化方向,您将每个dx,dy和dz除以此数字。

如果您想朝那个方向移动,新位置是旧位置加 方向向量乘以您想要行进的距离:

newpos = oldpos + dist * dirvector

我不确定你input: (100, 200, -200)的意思,如果这是方向, 你的方向向量是300长,实际的方向向量是 100 / 300,200 / 300和-200/300(所以0.333,0.667和-0.667)

如果你想沿着这个方向旅行500,新的位置是 0 + 166.67,0 + 333.33和0-333.33

相关问题