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

Positioning a Gameobject to stay in screen center always


I'm trying to position a gameobject to stay at the center of the screen always. I'm using the following code to do so,

sphere.SetActive(true);
Vector3 lookAtPosition = FirstPersonCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, FirstPersonCamera.nearClipPlane));
sphere.transform.position = lookAtPosition;

But for some reason, the gameobject is not visible at all with the above code.

So, I tried to raycast it and make it visible.

Following is the corresponding code,

TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon | TrackableHitFlags.FeaturePointWithSurfaceNormal;

TrackableHit hit;
if (Frame.Raycast(screenCenter.x, screenCenter.y, raycastFilter, out hit))
{
    var pose = hit.Pose;

    sphere.SetActive(true);
    sphere.transform.position = pose.position;
    sphere.transform.up = pose.up;
}

The gameobject shows up occasionally with the above code but it is not centered exactly to the screen and it is not showing up forever. How can I be able to sort it out?


Solution

    • It could be that your object is on top of the camera and outside in its field of view
    • A problem on its sorting layer

    A screenshot of your inspector and scene window might help.