- Home /
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.
demo.jpg
(25.6 kB)
Comment
Best Answer
Answer by KellyThomas · Dec 13, 2013 at 06:24 AM
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.
Your answer
Follow this Question
Related Questions
Show/Hide Mouse on Screen Position 1 Answer
UI RectTransform Position && Screen Resolution 2 Answers
Touch.position, Touch.deltaPosition, Screen.width, Screen.Height 1 Answer
Change Position of an object 1 Answer
Lock the screen 1 Answer