- Home /
Do something when mouse cursor "hits / looks at" object
Hi,
At the moment I have a simple crosshair in the center of the screen. This functions as the mouse pointer and always stays in the center of the screen.
In my scene there are a few boxes placed with the tag "box". What I want is that a "Debug.Log" text is shown once my mouse goes over this object. So basically when I move the crosshair onto the object, a text has to be shown in the console. How do I find out if the cursor "aims" at the object? I am using javascript and a First Person Controller. This may ONLY work on objects with the tag "box".
You can detect the boxes with a raycast and a specific layer ins$$anonymous$$d of a tag : http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
Answer by DragonSaige · Sep 13, 2012 at 01:32 PM
function OnMouseEnter() can be used here, it is called when the mouse hovers over a gameobject or texture (more precisely a Collider or GUI element).
Here's a demonstration
function OnMouseEnter() {
Answer by AlucardJay · Sep 13, 2012 at 01:37 PM
Raycast from the position of the cursor, check the name or tag of the collider returned from the raycast, if so then DoStuff();
var rayMousePos = Camera.main.ScreenPointToRay(Input.mousePosition);
var rayHit : RaycastHit;
if ( Physics.Raycast(rayMousePos, rayHit) )
{
Debug.DrawLine( rayMousePos.origin, rayHit.point );
Debug.Log( " Ray Hit Name : " + rayHit.collider.gameObject.name );
Debug.Log( " Ray Hit Tag : " + rayHit.collider.gameObject.tag );
}
http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
wow, i was way too slow =]
one accepted answer, one comment with my answer !