【问题标题】:Rotating object relative to mouse position相对于鼠标位置旋转对象
【发布时间】:2013-05-25 02:58:12
【问题描述】:

目前我正在使用鼠标位置和 (0, 1) 的点积来生成弧度来旋转对象,在三个.js 中

下面的代码,工作正常,但对象“跳跃”,因为当clientX 值介于window.innerWidth / 2 之间时,弧度角从正跳到负

onDocumentMouseMove : function(event) {
    // rotate circle relative to current mouse pos

    var oldPos = new THREE.Vector2(0, 1);


    Template.Main.mouseCurrPos = new THREE.Vector2((event.clientX / window.innerWidth ) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1);


    Template.Main.mouseCurrPos.normalize();
    //Template.Main.projector.unprojectVector(Template.Main.mouseCurrPos, Template.Main.scene);

    var angle = oldPos.dot(Template.Main.mouseCurrPos);
    Template.Main.mousePrevPos.x = event.clientX;
    Template.Main.mousePrevPos.y = event.clientY;


    if (event.clientX < window.innerWidth / 2) {
        Template.Main.circle.rotation.z = -angle;
    }
    else {
        Template.Main.circle.rotation.z = angle;
    }

    console.log(Template.Main.circle.rotation.z);
}

但是,如果我添加它以将值分配给 oldPos:

    if (event.clientX < window.innerWidth / 2) {
        oldPos = new THREE.Vector2(0, -1);
    }
    else {
        oldPos = new THREE.Vector2(0, 1);
    }

然后“跳跃”消失,但当鼠标在窗口左侧时,旋转效果反转。

即鼠标上移会逆时针旋转,反之亦然,这是不希望的。

这令人沮丧。

另外,如果我保留 oldPos 条件赋值并省略角度的条件否定,跳跃就会回来。

您可以在此处查看演示:http://theworldmoves.me/rotation-demo/

非常感谢任何提示。

【问题讨论】:

  • 你希望鼠标如何影响旋转?

标签: graphics geometry three.js dot-product


【解决方案1】:

您为什么使用点积的结果作为角度(弧度)?点积为您提供余弦角度(乘以向量的大小,但这些是单位向量和归一化向量,所以没关系)。

您可以将角度计算更改为

var angle = Math.acos(oldPos.dot(Template.Main.mouseCurrPos));

但是,您可能会得到错误的象限,因为可能有两个满足 cos(theta) = ntheta 值。获取右象限中向量角度(鼠标位置的原点)的常用方法是使用 atan2():

var angle = Math.atan2(Template.Main.mouseCurrPos.y,
                       Template.Main.mouseCurrPos.x);

这应该给出鼠标位置向量的角度,从 (1, 0) 开始逆时针方向。稍作实验就可以确定零角在哪里,哪个方向是正转。

【讨论】:

  • 读完之后,我意识到我以前做过这个! atan2 是当时的解决方案,就像现在一样,谢谢。
  • @AlexW:似曾相识……这有时会发生在我身上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2014-04-22
  • 2012-10-20
相关资源
最近更新 更多