Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A-Frame Trigger javascript function on collide with camera

I am trying to trigger my score function whenever the camera collide or touch an object like:

<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>

I equip my a score text on my camera:

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

And trying to trigger a function like this:

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

This is just a draft up code, I am still new to javascript

How can i do this? Incrementing the score on the screen whenever my camera touches this "rock" object?

How can i detect the collision or touch with the object and my camera?

Thanks in advance.


2 Answers

The simplest way to detect collisions would be detecting if the THREE bounding boxes are overlapping

You can use Ngo Kevins aabb-collider which emits hitstart upon collision. Remember though, the camera does not have it's own geometry:

<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>

with foo being a simple event listener for hitstart.

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

Fiddle here.

If possible, I wouldn't detect collisions with your model, but create some collision boxes.


It's also worth mentioning, if You'd want to use a physics engine in your project, Don McCurdys Physics System also enables collision detection. Instead of hitstart, You'd need to listen for collision.

like image 178
Piotr Adam Milewski Avatar answered May 02 '26 04:05

Piotr Adam Milewski


Just do this:

score++;
$("#score").attr("value", score);
like image 43
Jack Bashford Avatar answered May 02 '26 04:05

Jack Bashford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!