Search code examples
c#unity-game-engineaugmented-realityvuforia

Force an AR object to always stand upright in Unity / Vuforia


I have a Unity AR project using Vuforia engine. What I am trying to achieve is to have the AR object always stand upright in the view whether the image target is horizontal on a table or or vertical on a wall.

Currently the object is sitting on the image target no matter which orientation

Hope that makes sense,

Thanks


Solution

  • I always use Vector3.ProjectOnPlane for this and then you can simply assign axis directions to Transform.up and Transform.right (below I explain why right and not maybe forward)

    public void AlignObject(Transform obj, Transform imageTarget)
    {
        obj.position = imageTarget.position;
    
        // Get your targets right vector in world space
        var right = imageTarget.right;
    
        // If not anyway the case ensure that your objects up vector equals the world up vector
        obj.up = Vector3.up;
    
        // Align your objects right vector with the image target's right vector
        // projected down onto the global XZ plane => erasing its Y component
        obj.right = Vector3.ProjectOnPlane(right, Vector3.up); 
    }
    

    The assumption for this is: The target is usually never rotated in the Z axis. If you want it upright on a wall you would usually rotate it around its X axis.

    Therefore we can assume the the image target will never be rotated more then 90° on the Z axis (in which case the mapped vector would flip about 180°) and thus if we map the right vector down onto the global XZ plane it always still points in the correct direction regardless of any rotations in Y and X axes.

    If we would use the forward instead we take the risk that due to tracking inaccuracies the vertical targets forward vector actually points a tiny little bit towards us so when we map it down onto the XZ plane it points backwards not forwards and the object is flipped by 180°.

    So using right works for a horizontal and a vertical target.