Aidan Young
Aidan Young

Reputation: 614

A-frame trigger function when two objects touch

I am wondering how I can achieve something in A-frame where when two objects touch, a function called myFunction() is triggered with a one second delay. This means that if the objects are continuously touching, there will be a 1 second delay before the next function is triggered. How can this be done? Simple example:

<html>
  <head>
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
  </head>
  <body>
    <a-scene>
      <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
      <a-sky color="#ECECEC"></a-sky>
    </a-scene>
  </body>
</html>

I would ideally like to trigger a function each 1 second called myFunction that the sphere and square are touching. How can this be done?

Upvotes: 1

Views: 628

Answers (1)

msenne
msenne

Reputation: 613

You may try setting a class on each object you want to monitor:

<a-box class="collidable" position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
<a-sphere class="collidable" position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>

Then attach collision event handlers with a 1 second delay event handler in each:

function collisionHandler (event) {
  console.log('Entity collided with', event.detail.collidingEntity);
  setTimeout(() => {
    console.log('one second later...', event.detail.collidingEntity);
  }, 1000)
}

const collidables = document.querySelectorAll('.collidable');
console.log(`collidables ${collidables.length}`);
collidables.forEach(cld => {
    cld.addEventListener('physicscollided', collisionHandler);
})

See example here, but you'll have to figure out how to move the objects: https://jsfiddle.net/mq9xwraf/4/

One problem is that you're going to receive events from either object on each collision (it takes two to tango, as they say). You would need to decide how to resolve that duplication of events.

Upvotes: 1

Related Questions