基于鼠标光标控制Torus(圆环)朝向的问题排查
问题:鼠标控制圆环跟随的Y轴旋转异常及旋转对象需求
我正尝试实现通过鼠标光标控制圆环(Torus)跟随移动的功能,但Y轴存在异常:画布边缘区域表现正常,但光标移至中心时,圆环会疯狂旋转。请问是否可以限制旋转角度?另外,能否直接旋转圆环本身而非相机?目前我仅找到控制相机的实现方式,但这不符合预期。
原代码
HTML引入
<script src="https://cdn.jsdelivr.net/npm/p5@1.8.0/lib/p5.js"></script>
JavaScript实现
let torusRotationY = 0 function setup() { createCanvas(windowWidth, windowHeight, WEBGL) torusRotationY = HALF_PI // 初始让圆环旋转90度 } function draw() { background(0) orbitControl() const targetX = mouseX - width / 2 const targetY = mouseY - height / 2 const targetZ = 0 const distance = 400 const target = createVector(targetX, targetY, targetZ) const cameraPosition = target.copy().normalize().mult(-distance) camera(cameraPosition.x, cameraPosition.y, cameraPosition.z) push() normalMaterial() rotateY(torusRotationY) torus(80, 45) pop() torusRotationY = atan2(targetX, distance) + HALF_PI }
解决方案
修改后的代码
let torusRotationY = 0; let smoothRotationY = 0; // 用于平滑旋转的过渡变量 const rotationSmoothing = 0.1; // 平滑系数,数值越小旋转越平缓 const maxRotation = PI / 3; // 限制最大旋转角度为60°(可自行调整) function setup() { createCanvas(windowWidth, windowHeight, WEBGL); torusRotationY = HALF_PI; // 初始旋转90° } function draw() { background(0); // 固定相机位置,不再随鼠标移动 camera(0, 0, 400); const targetX = mouseX - width / 2; // 计算目标旋转角度 let targetRotation = atan2(targetX, 400) + HALF_PI; // 限制旋转角度范围,避免过度旋转 targetRotation = constrain(targetRotation, HALF_PI - maxRotation, HALF_PI + maxRotation); // 平滑过渡到目标角度,解决中心区域旋转突变问题 smoothRotationY += (targetRotation - smoothRotationY) * rotationSmoothing; torusRotationY = smoothRotationY; push(); normalMaterial(); rotateY(torusRotationY); // 让圆环跟随鼠标Y轴移动(乘以0.5降低移动幅度,可调整) translate(0, (mouseY - height / 2) * 0.5, 0); torus(80, 45); pop(); }
关键改动说明
- 固定相机,直接控制圆环:移除原相机跟随逻辑,将相机固定在(0,0,400)位置,改为直接旋转和移动圆环本身,符合需求。
- 解决中心旋转疯狂问题:添加平滑过渡变量
smoothRotationY,通过插值算法让旋转角度逐步趋近目标值,避免鼠标在中心时的角度突变;同时使用constrain()限制旋转范围,防止过度旋转。 - Y轴跟随优化:添加
translate()实现圆环随鼠标Y轴移动,可通过调整乘数控制移动幅度。
内容的提问来源于stack exchange,提问作者SubRight
相关产品推荐
相关产品推荐

