- Home /
How can I add a distance cap to this script?
I found this script on the Unitywiki, Whenever the mouse cursor is over an object in my scene that has this script attached to it it displays a image. The only thing left that I need to do to this script is make it so you have to be within a certain distance of this object. As of now I could be infinite away from it and if i hover over it it will still display the image. I'm looking at trying to restrict it from doing so unless within say 3.5 feet. Any help would be greatly appreciated.
using UnityEngine; using System.Collections;
public class MouseManipulateIcon : MonoBehaviour
{
public Texture2D cursorImage;
private int cursorWidth = 48;
private int cursorHeight = 48;
private bool showCursor = false;
private string defaultResource = "MousePointer";
void Start()
{
if(!cursorImage) {
cursorImage = (Texture2D) Resources.Load(defaultResource);
Debug.Log(cursorImage);
}
//cursorImage = (Texture2D) Instantiate(cursorImage);
}
void OnMouseEnter()
{
Debug.Log("Entered");
Screen.showCursor = false;
showCursor = true;
}
void OnGUI() {
if(showCursor) {
GUI.DrawTexture(new Rect(Input.mousePosition.x, Screen.height - Input.mousePosition.y, cursorWidth, cursorHeight), cursorImage);
}
}
void OnMouseExit()
{
Debug.Log("Left");
showCursor = false;
Screen.showCursor = true;
}
}
Answer by voodoo · Dec 30, 2012 at 04:30 AM
Check that the distance between the object's position and the camera's position is less than a specified float (in meters) before you do your logic.
Answer by mel1992 · Dec 30, 2012 at 04:30 AM
Well you can do it different ways. One way is to check the distance to the MainCamera:
void OnMouseEnter()
{
if (Vector3.Distance(Camera.main.transform.position,transform.position) > 5)
{
Debug.Log("Entered");
Screen.showCursor = false;
showCursor = true;
}
else
{
Debug.Log("Left");
showCursor = false;
Screen.showCursor = true;
}
}
or you can send a raycast out from the Camera in an Update():
void Update()
{
RaycastHit hitInfo;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 3.5f)), out hitInfo) && hitInfo.collider.gameObject.name == "The name of Object")
{
Debug.Log("Entered");
Screen.showCursor = false;
showCursor = true;
}
else
{
Debug.Log("Left");
showCursor = false;
Screen.showCursor = true;
}
}
Answer by Straight Rainbow · Dec 30, 2012 at 03:55 AM
You could do a simple Vector3.Distance(transform.position,Camera.mainCamera.transform.position); or you can modify to to do a Ray collision test and make a distance limitation on that.