有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将对象旋转到面点

我想旋转一个物体来面对一个我有点麻烦的点

我从一个物体开始,这个物体的底面为零,并且在y轴上对齐

enter image description here

我想旋转它,使对象的顶部朝向目标

enter image description here

到目前为止,我的过程是: 给定轴A

  1. 找到我的位置和我的注视位置之间的距离:D
  2. 创建方向向量:V=D.normalize()
  3. 找到正确的向量:R=A交叉点D
  4. 求上方向向量:U=D交叉R
  5. 求向上和方向之间的角度:角度=acos((U点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);

共 (1) 个答案

  1. # 1 楼答案

    这里的基本思想如下

    • 确定对象面对的方向: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