相对于鼠标位置旋转对象

时间:2013-05-29 18:00:24

标签: graphics geometry three.js dot-product

目前我正在使用鼠标位置的点积和(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/

非常感谢任何提示。

1 个答案:

答案 0 :(得分:1)

为什么使用点积的结果作为角度(弧度)?点积给出 角度的余弦(向量的大小乘以,但这些是单位向量和归一化向量,因此无关紧要。)

您可以将角度计算更改为

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

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

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

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