Search code examples
javascripthtmljqueryaframewebvr

A-frame add an<a-cursor> onclick event with an entity


I have been working on a vr scene and I'm wondering how I can add an <a-cursor> to my scene and create an onclick event with the <a-entity> at the bottom of my code. I would like it so that when I click with my <a-cursor> on the <a-entity>, a function called myFunction() should occur. How can I accomplish this? My fiddle: fiddle


Solution

  • To add an <a-cursor> to your scene, you'll want to place it as a child of <a-camera> first inside your scene.

    <a-scene update-html>
          <a-camera>
            <a-cursor></a-cursor>
          </a-camera>
    

    It should show as a small ring. For A-Frame, I would create a component like so:

        <title>A-Frame HTML Shader - Dynamic</title>
        <script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
        <script src="https://unpkg.com/aframe-html-shader@0.2.0/dist/aframe-html-shader.min.js"></script>
        <script>
          AFRAME.registerComponent("click-log", {
            init: function() {
              this.myFunction = function() {
                console.log("hi");
              };
    
              this.el.addEventListener("click", this.myFunction);
            },
    
            remove: function() {
              this.el.removeEventListener("click", this.myFunction);
            }
          });
    
        </script>
    

    And place this in the head of my file with the other scripts. Then, adding this to the box like so:

    <a-entity id="lettersEntity" click-log...
    

    Fiddle here.

    This will write to the console "hi" whenever our cursor is placed over the attached entity and we click. Components are useful for keeping things modular so if we wanted to add another box later on we could click on and also log, we would just add click-log to it as well. We could also add more functions to click-log that trigger on different event listeners. Init will add our event listener on creation, and remove will clean it up so we don't have leftover event listeners if we remove the entity its attached to later.

    If you're interested in using your mouse as a cursor instead, A-Frame v0.6.1 and up support <a-scene cursor="rayOrigin: mouse">, which can be easier to use than the a-cursor primitive.

    This series might also be helpful, as this video specifically also covers working with components and event listeners better than I can. It shows how to do things like change colors of an A-Frame primitive on click, for example.