Search code examples
javascriptaugmented-realityaframe

A-Frame: make model face the viewer / center of the screen or canvas


I've been trying to make my model in a-frame always face the viewer. So far I've been trying to achieve this using the camera component, both via look-at in a-entity:

<a-entity id="entity" look-at="[camera]"></a-entity>

And by adding a script into the body:

document.querySelector('#ebtity').object3D.lookAt('#camera');

The camera is default:

<a-entity id="camera" camera look-controls></a-entity>

However it looks like the camera component does not represent the real world camera position.

All I need is for the model to face the viewer - or in other terms, always face the center of the screen or canvas.

Anybody got any advice on how to get this done?


Solution

  • Your on the right track,

    The simplest way to achieve this is to register a custom component to have one entity face another entity

    AFRAME.registerComponent('look-at', {
      schema: { type: 'selector' },
    
      init: function () {},
    
      tick: function () {
        this.el.object3D.lookAt(this.data.object3D.position)
      }
    })
    

    The selector type in the schema already runs document.querySelector() so we just need to access it through this.data

    The tick function is ran every frame to continuously update the objects rotation to the target

    In your scene your camera gets an id and you pass it into our defined look-at component

    <a-entity id="camera" wasd-controls camera look-controls position="0 1.5 0"></a-entity>
      
    <a-plane look-at="#camera" ></a-plane>
    

    here is a working example https://glitch.com/edit/#!/amusing-nervous-jaxartosaurus?path=index.html%3A13%3A7