【问题标题】:ThreeJS : How to get the angle between2 object三JS:如何获得2个对象之间的角度
【发布时间】:2022-11-03 01:35:59
【问题描述】:
  • 我在给定位置 (v0) 和旋转 (r0) 有一个头像
  • 我在给定位置有一个对象 (v1)

我正在寻找将头像向 v1 旋转的角度。我需要角度我不想使用lookAt() 函数

// Get the Avatar Position
let v0 = new THREE.Vector3();
avatar.getWorldPosition(v0)

// Get the Object Position
let v1 = new THREE.Vector3();
obj.getWorldPosition(v0)

// Get the direction v0 to v1
let dir0 = new THREE.Vector3();
dir0.subVectors( v0, v1 ).normalize();

// Get the direction of avatar (where it look at)
let dir2 = new THREE.Vector3();
avatar.getWorldDirection(dir2)

// Get the angle between the 2 direction
let radians =  dir0.angleTo(dir2)

它不起作用!

  • this.mesh.lookAt(v1.setY(0)) 工作并正确旋转网格
  • 但是由于avatar.getWorldDirection,角度计算不起作用
  • 顺便说一句,因为一切都在同一个平面上,所以我不需要 3D(只有 2D)
  • 顺便说一句,头像(Mixamo)似乎面朝后

我需要那个角度来触发一些动画(如果角度> 90,则触发90,如果角度> 180,则返回动画......)

【问题讨论】:

    标签: three.js mixamo


    【解决方案1】:

    您的代码有一些错误。 obj.getWorldPosition(v0) 将覆盖用avatar.getWorldPosition(v0) 检索到的v0 值,因此当您减去v0 - v1 时,您将得到一个大小为0 的向量。

    查看the documentation of Vector3.angleTo(),它说您需要做的就是输入位置,无需任何减法:

    let posAvatar = new THREE.Vector3();
    avatar.getWorldPosition(posAvatar);
    
    
    let posObj = new THREE.Vector3();
    obj.getWorldPosition(posObj);
    
    const angleRadians = posAvatar.angleTo(posObj);
    
    // convert from radians to degrees
    const angleDeg = THREE.MathUtils.radToDeg(angleRadians);
    

    请记住,两个对象都需要在同一平面上才能使此 2D 角度准确。

    更新:

    此方法使用the Javascript Math.atan2() method 计算从您的化身有利位置到 obj 的绝对 y 轴旋转。这也仅使用 x,z 位置,因此忽略任何高度变化。

    let posAvatar = new THREE.Vector3();
    avatar.getWorldPosition(posAvatar);
    
    let posObj = new THREE.Vector3();
    obj.getWorldPosition(posObj);
    
    const xDist = posObj.x - posAvatar.x;
    const zDist = posObj.z - posAvatar.z;
    const angle = Math.atan2(zDist, xDist) * 180 / Math.PI;
    

    【讨论】:

    • 是的,这是第一个错字。
    • 我从 2 个位置尝试了 angleTo,然后设置了 mesh.rotation.y += 弧度,但多次调用仍然在循环中执行旋转。弧度是一样的。你如何设置弧度?
    • 只需将旋转设置为其绝对值:mesh.rotation.y = radian;,不带+= 符号。如果在循环中多次执行计算,+= 符号将不断添加和添加更多旋转。
    • 很奇怪,如果我转过头像,我仍然会得到 9 到 18 度,它应该是更多
    • 嗯......在考虑了更多之后,我认为采用这种.angleTo() 方法可能是有缺陷的。两点之间的角度并不意味着这是 y 轴旋转。例如,两点之间的角度可以是 90 度,但其最终旋转可能是 180 度。今天晚些时候我会再考虑一下,看看我是否可以更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2018-12-29
    相关资源
    最近更新 更多