旋转物体以面向点

9
我想将一个基于y轴对齐,底部位于零点的物体旋转以面对目标点,但遇到了一些困难。
我已经完成了以下步骤: 给定轴 A
  1. 计算我的位置和观察位置之间的距离:D
  2. 创建方向向量:V = D.normalize()
  3. 查找正确的向量:R = A cross D
  4. 查找上方向向量:U = D cross R
  5. 查找上向量与方向之间的角度:ANGLE = acos((U dot D) / (U.length * D.length))
  6. 按比例在每个轴上旋转该角度
这是代码表示。我不确定哪里出了问题,我已经在纸上计算过,并且根据我的知识,这种方法应该有效,但绘制结果完全不正确。如果有人发现任何错误并能指导我正确方向,那将会很好。
    Vector3 distance = new Vector3(from.x, from.y, from.z).sub(to.x, to.y, to.z);
    final Vector3 axis = new Vector3(0, 1, 0);
    final Vector3 direction = distance.clone().normalize();

    final Vector3 right = (axis.clone().cross(direction));
    final Vector3 up = (distance.clone().cross(right));

    float angle = (float) Math.acos((up.dot(direction)/ (up.length() * direction.length()))); 
    bondObject.rotateLocal(angle, direction.x , direction.y, direction.z);

我认为你的数学存在问题。在第5步中,你计算“上”向量和方向向量之间的角度,但是这个角度将始终为90度。U = D cross R,因此按定义,U垂直于D和R,并且点积U·D将始终为零。如果你能更明确地说明你要实现什么目标,我可以为你找到更好的公式。 - mikebolt
谢谢回复,我正在尝试将物体旋转以面向一个点,所以如果我的物体在(0,0,0),而该点在(0,0,1),我希望圆柱体朝向z轴向下(包围z轴的管道)。我尝试提供上面的图像,但我的绘画技能有些欠缺^^ - William Gervasio
1个回答

20

这里的基本思路如下。

  • 确定物体面向的方向:directionA
  • 确定物体应该面向的方向:directionB
  • 确定这些方向之间的角度:rotationAngle
  • 确定旋转轴:rotationAxis

这是修改后的代码。

Vector3 distance = new Vector3(from.x, from.y, from.z).sub(to.x, to.y, to.z);

if (distance.length() < DISTANCE_EPSILON)
{
    //exit - don't do any rotation
    //distance is too small for rotation to be numerically stable
}

//Don't actually need to call normalize for directionA - just doing it to indicate
//that this vector must be normalized.
final Vector3 directionA = new Vector3(0, 1, 0).normalize();
final Vector3 directionB = distance.clone().normalize();

float rotationAngle = (float)Math.acos(directionA.dot(directionB));

if (Math.abs(rotationAngle) < ANGLE_EPSILON)
{
    //exit - don't do any rotation
    //angle is too small for rotation to be numerically stable
}

final Vector3 rotationAxis = directionA.clone().cross(directionB).normalize();

//rotate object about rotationAxis by rotationAngle

1
非常感谢,第一次尝试就完美解决了!我没有15个声望,所以现在还不能为你的答案点赞,但我会在有机会时给你点赞。 - William Gervasio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接