Search code examples
javascriptthree.jsaframear.js

How to use look-at feature in Ar.js programatically


I am trying to use the look-at feature of Ar.js dynamically through js. But for some reason, the 3d-object is not looking out of the screen.


Solution

  • Answering the topic

    You can set the look-at component using javascript, by adding it to any a-frame entity:

    // using an existing entity as a target
    entity.setAttribute("look-at", "#selector");
    // using a Vector3 position as target 
    entity.setAttribute("look-at", {x: 0, y: 0, z: 0})
    

    Answering this specific case

    The look-at component (and the used by it lookAt method) assume, that the model is orented towards the z-axis.

    The duck model is oriented towards the x axis. If it's possible, reorient the model in a 3D modelling software like blender. If not, then you can use a parent node to reorient it:

    <!-- Parent node will look at the user--/>
    <a-entity look-at="[camera]">
        <!-- Child node with the rotation offset--/>
        <a-entity rotation="0 -90 0" gltf-model ....>
    

    Check it out in this glitch
    If there are more models, you can create a rotation offset array, and apply it to the [gltf-model] node each time you load a new model.


    The <a-camera> already contains a camera. To change its properties just use the <a-camera> attributes:

    <a-camera fov="60" ....></a-camera>