如何修改A-frame代码实现仅相机Y轴移动距离超10时触发复位
A-frame相机Y轴偏移限制修改方案
原逻辑问题
原代码使用distanceTo()方法计算相机当前位置到起始点的三维空间总直线距离,只要X、Y、Z任意轴累计偏移导致总距离超过10就会触发复位,不符合仅判断Y轴偏移的需求。
完整修改后代码
<!DOCTYPE html> <html lang="en"> <head> <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script> <meta charset="UTF-8" /> </head> <body> <script> AFRAME.registerComponent('limit-my-distance', { init: function() { // 记录起始点Y坐标,可根据需求调整初始基准Y值 this.originY = 0; }, tick: function() { // 仅判断Y轴偏移量的绝对值是否超过10 if (Math.abs(this.el.object3D.position.y - this.originY) > 10) { this.el.object3D.position.set(0, 1.6, 0); } } }); </script> <a-scene> <a-sphere position="0 2 -10" color="red"></a-sphere> <a-plane color="green" position="0 0 -5" rotation="-90 0 0" width="20" height="20"></a-plane> <a-camera limit-my-distance></a-camera> <a-sky color="#fff"></a-sky> </a-scene> </body> </html>
关键修改说明
- 移除了原来的三维距离计算逻辑,改为单独获取相机Y轴坐标和起始Y坐标的差值
- 使用
Math.abs()计算偏移绝对值,同时覆盖Y轴向上、向下两个方向的偏移判断;若仅需要限制单方向偏移(比如仅禁止Y轴高于10),可以直接去掉Math.abs(),调整判断条件为this.el.object3D.position.y > 10即可 - 可根据实际需求修改
this.originY的初始值,适配不同的起始基准位置
内容的提问来源于stack exchange,提问作者Aidan Young
相关产品推荐
相关产品推荐

