Cursor track object

Hello.
I have a GUI cursor that follows a moving object on screen, I’m using the following script for this:

public var cursor : Texture;
function OnGUI(){
    var point = Camera.main.WorldToScreenPoint(transform.position);
    if (Time.timeScale != 0)
    GUI.DrawTexture(new Rect(point.x - cursor.width/2, Screen.height - point.y - cursor.height/2, cursor.width, cursor.height), cursor);
}

But I want the cursor stays on the edge of screen when the object goes out of screen.
I hope you understand , don’t know well how to explain I’ll try with an image.

Thanks.

1 Answer

1

Mathf.Clamp() can do what you want:

public var cursor : Texture;
function OnGUI(){
    var screenPoint: Vector3 = Camera.main.WorldToScreenPoint(transform.position);

    var halfWidth = cursor.width/2;
    var halfHeight = cursor.width/2;
    var clampedPoint = new Vector3(
             Mathf.Clamp(screenPoint.x, halfWidth, Screen.width - halfWidth),
             Mathf.Clamp(screenPoint.y, halfHeight, Screen.height - halfHeight),
             screenPoint.z);

    if (Time.timeScale != 0) {
        var rect:Rect = new Rect(
            clampedPoint.x - halfWidth,
            Screen.height - clampedPoint.y - halfHeight,
            cursor.width,
            cursor.height);
        GUI.DrawTexture(rect, cursor);
    }
}

Thankyou , it was obvious a Clamp, never thought about it. Now my idea is change the cursor image when off screen, but I get it.