How to detect screen's edge and not pass it?

I made cursor for user to move it and use it as selection standard like Mouse cursor on PC platform.

Then how to detect current screen’s edge for this cursor image object not pass over screen’s edge?

Screen’s resolution is different as running platform, like unity editor, console screen, mobile screen, but should work on all of them.

How to?

I wrote some code, but this seems not work well.

Cursor gameobject is below canvas and its default local position is 0, 0, 0

void Update()
    {
        if (CursorIsOn)
        {
            UpdateCursorMove();
        }
    }
    public void UpdateCursorMove()
    {
        float newX = SelectionCursor.transform.localPosition.x + CursorSpeed;
        float newY = SelectionCursor.transform.localPosition.y + CursorSpeed;

        Vector3 screenPos = Camera.main.WorldToScreenPoint(SelectionCursor.transform.position);

        if (newX < -Screen.width / 2)
            newX = -Screen.width / 2;
        if (newX > Screen.width)
            newX = Screen.width;
        if (newY < -Screen.height / 2)
            newY = -Screen.height / 2;
        if (newY > Screen.height / 2)
            newY = Screen.height / 2;
        SelectionCursor.transform.localPosition = new Vector3(newX, newY, 0);
    }

If this code is driving an object in a UI hierarchy, just make invisible blank markers anchored to the lower left and upper right of the Canvas and use those as your bounds.

1 Like