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

2024-09-30 08:26:43 发布

您现在位置: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)开始的示例。我试图使输出与输入相似,如果不是相同的话。在

输入:(100200,-200)

矢量1航向(弧度):1.1071487177940904 矢量2航向:2.356194490192345

向量1距离:223 向量2距离:282

输出:(99.7286317964909199.4572635929818181157.68481220460077) x和y没问题,但z关了。在

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

矢量1航向(弧度):1.9257588105240444 矢量2航向:1.6039072496758664

向量1距离:676 向量2距离:634

输出:(-220.3499891866359594.4761410396925633.6524941214135) z关闭。在


Tags: self距离矢量mathcoords向量distancespeed
1条回答
网友
1楼 · 发布于 2024-09-30 08:26:43

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

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

对于规格化方向,将每个dx、dy和dz除以该数字。在

如果你想往那个方向走,新的位置就是旧的位置加上 方向向量乘以要移动的距离:

新位置=旧位置+距离*方向向量

我不知道你说的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

相关问题 更多 >

    热门问题