Search code examples
user-interfaceunity-game-enginegameobject

Unity 3D : UI Image in the direction of a game object


I'll explain my issue (My English is a little lame sorry).

I have a Player ( Camera) who is able to move in a Unity Scene. In this scene there is some GameObjects. Those GameObjects May be too far for the camera to see. What I want to achieve is to have an UI Image that appear in the direction of every objects. Even if the objects are too far.

Example : The player stand at a position. In front of him there is an object that is far. I want to have a GUI on screen who says "there is an object at 200 m ". If there is an object behind him I dont want anything to appear. But if he turns back, it will appear cause the player is in the direction of the said GameObject.

I really hope I made myself clear. Please tell me if you need any further explanations. Thank You community !


Solution

  • Answering to an old question of myself :

    Here's what I did :

    if (markIsOp)  //Check if it's worth calculating
    {
    
           //Calculs the Viewport Position of the object
            Vector3 ViewportPosition = Camera.main.WorldToViewportPoint (transform.position);
    
            //Calculs it's Unity Canvas position (O.5f because UI anchor is middle)
            Vector2 WorldObject_ScreenPosition = new Vector2 (
                                                    ((ViewportPosition.x * mainCanvasRect.sizeDelta.x) - (mainCanvasRect.sizeDelta.x * 0.5f)),
                                                    ((ViewportPosition.y * mainCanvasRect.sizeDelta.y) - (mainCanvasRect.sizeDelta.y * 0.5f)));
    
            //Making sure it's forward (markRect is my UI Element's RectTransform)
            if (ViewportPosition.z > 0)
                markRect.anchoredPosition = WorldObject_ScreenPosition;
    }   
    

    Thank you for your responses. Have a nice one