首页 > 解决方案 > 与相机碰撞时的 A-Frame Trigger javascript 函数

问题描述

每当相机碰撞或触摸物体时,我都会尝试触发我的评分功能,例如:

<a-entity id="rock" static-body obj-model="obj:models/rock_mesh.obj;mtl:images/rock_mesh.mtl" rotation="0 90 0" position="7.30242379045994 0.3 0">
     </a-entity>

我在我的相机上装备了我的乐谱文本:

 <a-text id="score" value="0" position="-0.2 -0.5 -1" color="red" width="5" anchor="left"></a-text>

并尝试触发这样的功能:

let score = 0;
score = score + 1
$("#score").setAttribute('text','value','Score '+score)

这只是一个草稿代码,我还是 javascript 新手

我怎样才能做到这一点?每当我的相机碰到这个“岩石”物体时,屏幕上的分数就会增加?

如何检测与物体和我的相机的碰撞或触摸?

提前致谢。

标签: javascriptjqueryhtmlwebpageaframe

解决方案


检测碰撞的最简单方法是检测三个边界框是否重叠

你可以使用 Ngo Kevins aabb-collider,它在碰撞时发射hitstart。但请记住,相机没有自己的几何形状:

<a-camera foo geometry="primitive: box" aabb-collider="objects: a-box"></a-camera>
<a-box scale="2 2 2" class="box" color="blue" position="0 1.6 -5" ></a-box>

foo 是一个简单的事件监听器hitstart

AFRAME.registerComponent("foo", {
  init: function() {
     this.el.addEventListener("hitstart", (e)=>{
         // Collision ! increment the score
     })
  }
})

在这里拉小提琴。

如果可能的话,我不会检测与您的模型的碰撞,而是创建一些碰撞框。


还值得一提的是,如果您想在项目中使用物理引擎,Don McCurdys Physics System 还可以启用碰撞检测。而不是hitstart, 你需要听collision.


推荐阅读