Issue with Camera.WorldToScreenPoint

Hey everyone !

I have a strange flipping issue (kind of) with worldtoscreenpoint.
I have a world with objects moving around along with a player and a camera following moving around aswell. I want to keep track of all objects positions and display an indicator of their position on screen when they are not seen by the camera (something like an arrow).

Im using this to check if the object is out of the screen and then putting it on the edge and it works :

bool IsOutOfScreen()
    {
        if (parent.anchoredPosition.x > Screen.width / 2 || parent.anchoredPosition.x < -(Screen.width / 2))
            return true;
        if (parent.anchoredPosition.y > Screen.height / 2 || parent.anchoredPosition.y < -(Screen.height / 2))
            return true;
        return false;
    }

    Vector2 IntersectionWithViewport(Vector2 _position)
    {
        Vector2 newPosition = Vector2.zero;

        if (Mathf.Abs(_position.x) >= Mathf.Abs(_position.y))
        {
            newPosition.y = _position.y / _position.x;
            newPosition.x = Mathf.Sign(_position.x);
        }
        else
        {
            newPosition.x = _position.x / _position.y;
            newPosition.y = Mathf.Sign(_position.y);
        }

        newPosition.x *= (Screen.width / 2);
        newPosition.y *= (Screen.height / 2);

        return newPosition;
    }

But the vector i get from worldtoscreenpoint that I give my method seems to be sometimes correct, sometimes flipped, I don’t really understand why.

Thanks if anyone can help ! :slight_smile:

It’s probably flipped if behind the camera. So, for your usage:

if (_position.z < 0.0f) _position = -_position;

Seems to be better but still not working for everything for some reasons
The problem might be coming from by intersection function now

Yes, I think you want to divide by the absolute value. So actually:

    Vector2 IntersectionWithViewport(Vector3 _position)
    {
        Vector2 newPosition = _position * Mathf.Sign(_position.z);
        float denominator = 2.0f * Mathf.Max(Mathf.Abs(_position.x), Mathf.Abs(_position.y));
        newPosition.x *= Screen.width / denominator;
        newPosition.y *= Screen.height / denominator;
        return newPosition;
    }

Ooooh you are so much better at maths than I am, seems to work, thanks ! :slight_smile:

Hey again !

The solution seems to work fine but the UI is not completely responsive, do you have any idea how to solve that ?