javascript - 将对象的位置用于 AFrame 中的事件
问题描述
我正在尝试制作一个组件来检查 AFrame 场景中球体的当前位置,以及当它击中特定坐标时以及触发事件时(在下面的示例中,它将其重置为默认位置):
AFRAME.registerComponent("trackball", {
update: function() {
let pos = this.el.getAttribute("position");
if (pos == {x:-21.821,y: 1,z: 0})
{
this.el.setAttribute("position", "-21.821 5 0");
}
}
});
我不确定.getAttribute("position")
调用时返回的格式是什么,这可能是它不起作用的原因。我正在运行 AFrame 1.1.0。
解决方案
首先在update
通过 更改属性时调用setAttribute()
。如果您想要在每个渲染帧上调用的函数,请使用tick()
.
其次,尝试使用范围而不是固定点,对象很可能会移动超过两个刻度之间的点。
像这样的东西:
<script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/n5ro/aframe-physics-system@v4.0.1/dist/aframe-physics-system.min.js"></script>
<script>
AFRAME.registerComponent("trackball", {
tick: function() {
let pos = this.el.getAttribute("position");
if (pos.y < 0.5) {
// reset position
this.el.setAttribute("position", "0 3 -4")
// sync
this.el.components["dynamic-body"].syncToPhysics();
}
}
});
</script>
<a-scene physics cursor="rayOrigin: mouse">
<a-sphere position="0 1.25 -5" radius="0.25" color="#EF2D5E" dynamic-body trackball></a-sphere>
<a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" static-body></a-plane>
<a-sky color="#ECECEC"></a-sky>
</a-scene>
在处理频繁调用的函数(当然适用于)时,也可以尝试使用object3D
属性:setAttribute()
getAttribute()
tick()
<script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/n5ro/aframe-physics-system@v4.0.1/dist/aframe-physics-system.min.js"></script>
<script>
AFRAME.registerComponent("trackball", {
// iife to initialize the "origin point" once
tick: (function() {
const origin = new THREE.Vector3(0, 3, -4);
const y_range = 0.5;
return function() {
// check if the ball is out of range
const pos = this.el.object3D.position
if (pos.y < y_range) {
// reset position
pos.copy(origin);
// sync
this.el.components["dynamic-body"].syncToPhysics();
}
}
})()
});
</script>
<a-scene physics cursor="rayOrigin: mouse">
<a-sphere position="0 1.25 -4" radius="0.25" color="#EF2D5E" dynamic-body trackball></a-sphere>
<a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" static-body></a-plane>
<a-sky color="#ECECEC"></a-sky>
</a-scene>
请记住,以这种方式更新位置性能更高,但会导致getAttribute("position")
通过返回最后一个位置设置setAttribute("position", new_position)
推荐阅读
- asynchronous - TCL中的fileevent非常慢
- android - 模拟 SharedPreferences.Editor.putString()
- tfs - 为什么 tfs 2018 部署组阶段将在前一个部分失败后运行?
- python - 如何使用 python 从 sqlite 获取数据?
- javascript - 无需jQuery UI即可在分隔符的拖放上调整Div大小
- batch-file - 批处理 - 功能 - 参数不起作用
- android - 在我的应用中显示受保护的版权视频
- html - 默认隐藏RPubs文档中的工具栏
- github - 在应用程序 GUI 上注释 github 问题
- c++ - 在 C++ 中初始化邻接矩阵