Search code examples
three.jsaframe

ARAME/THREE take camera rotation into account when position object in front of camera


Hi have a component that moves an object from its position into scene to a position in front of the camera.

This works fine if the camera has not been rotated, but I can't get it to account for the camera rotation when it has been rotated.

        //Copy the initial datas
        this._initialPosition = this._threeElement.position.clone()
        this._initialQuaternion = this._threeElement.quaternion.clone()

        //Convert fov + reduce it
        let fovInRad = AFRAME.THREE.Math.degToRad(this._cameraEntity.fov)/2
        let ratio=window.innerWidth/window.innerHeight //Assuming the FOV is vertical
        let pLocal,cPos

        let sizeY = this._size.y
        let sizeX = this._size.x
        let sizeZ = this._size.z

        sizeX*=this._threeElement.scale.x
        sizeY*=this._threeElement.scale.y
        sizeZ*=this._threeElement.scale.x

        const uSpace= 0.8
        sizeY/=2;sizeX/=2
        sizeY*=uSpace;sizeX*=uSpace

        let tanFov = Math.tan(fovInRad)
        let distY = sizeY/tanFov
        let distX = ((sizeX/(ratio*tanFov)) < distY) ? distY : sizeX/(ratio*tanFov)

        pLocal = new AFRAME.THREE.Vector3(0, 0, -(distX + sizeZ))
        cPos = this._cameraEntity.position.clone()
        cPos.y += 1.6

        this._targetPosition = pLocal.applyMatrix4(this._cameraEntity.matrixWorld.clone())
        this._threeElement.parent.worldToLocal(this._targetPosition)
        let targetLook = cPos.applyMatrix4(this._cameraEntity.matrixWorld.clone())
        this._threeElement.parent.worldToLocal(targetLook)
        this._threeElement.position.copy(this._targetPosition)
        this._threeElement.lookAt(targetLook)
        this._targetQuaternion = this._threeElement.quaternion.clone()

The issue seems to be when I apply the matrix of the camera.

Any idea how to find this target position relative to where the camera is facing


Solution

  • New three.vector3(0,0,-camera.near).applyQuaternion(camera.quaternion).add(camera.position)