You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ThreeJS对象绕自身Y轴旋转以朝向鼠标光标?

ThreeJS 立方体绕自身Y轴朝向鼠标光标旋转问题

我在ThreeJS中无法正确旋转一个从屏幕上方视角渲染的简单立方体,需要让它绕**自身Y轴(垂直轴)**旋转,始终朝向鼠标光标。目前只能实现让对象围绕屏幕中心的全局轴随光标旋转,没法绕自身局部轴旋转。


正交相机初始化代码

camera = new THREE.OrthographicCamera(
    window.innerWidth / - 2, // left
    window.innerWidth / 2, // right
    window.innerHeight / 2, // top
    window.innerHeight / - 2, // bottom
    0, // near
    1000 ); // far

camera.position.set(0, 0, 500)
camera.updateProjectionMatrix()

立方体对象初始化代码

const geometry = new THREE.BoxGeometry( 10, 10, 10 );
const material = new THREE.MeshBasicMaterial( { color: "grey" } );
const mesh = new THREE.Mesh( geometry, material );

初始尝试的鼠标旋转实现

方法一:直接设置rotation属性

function onMouseMove(event) {
    // 获取鼠标位置
    let mousePos = new THREE.Vector2();
    mousePos.set(
        (event.clientX / window.innerWidth) * 2 - 1, // x
        -(event.clientY / window.innerHeight) * 2 + 1); // y

    // 计算角度
    let angle = Math.atan2(mousePos.y, mousePos.x);

    // 为对象添加旋转
    mesh.rotation.set(
    0, // x
    angle, // y
    0) // z
}

方法二:使用rotateY方法

尝试调用mesh.rotateY(angle),但这会导致对象持续旋转,像直升机螺旋桨一样,不符合需求。

显然旋转逻辑需要基于光标与对象局部轴的相对关系,而非全局轴,但不知道如何实现。


最终解决方法(射线投射)

通过射线投射计算鼠标在平面上的交点,让立方体朝向该交点,实现绕自身Y轴朝向鼠标的效果:

let plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
let pointOfIntersection = new THREE.Vector3();
let raycaster = new THREE.Raycaster();

let mousePos = new THREE.Vector2();
mousePos.set(
    (event.clientX / window.innerWidth) * 2 - 1, // x
    -(event.clientY / window.innerHeight) * 2 + 1)

raycaster.setFromCamera(mousePos, camera);
raycaster.ray.intersectPlane(plane, pointOfIntersection);
mesh.lookAt(pointOfIntersection)

内容的提问来源于stack exchange,提问作者Candleout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:15:58