Hello!
I am quite new to unity, so sorry for the dumb question. I want to detect a mousedown on a game object (more specifically, I would like to know how many seconds the mouse button was held over the game object, and the position on the collider the click was done on).
A quick googling showed that there is two ways to detect mousedown: OnMouseDown() and raycast. I don’t know which one is better or quicker. Which one should I use? With OnMouseDown, can I have the coordinates where the user clicked on?
Currently I made a solution where I detect mouseclick with OnMouseDown/OnMouseUp, and in OnMouseUp I do a raycast to acquire a normal on the collider.
Thanks for the help,
Eszter
1 Answer
1
OnMouseDown goes in the object script, while raycast may be in a script attached to anything. OnMouseDown is easier when you must detect if the object was clicked - but you don’t know exactly where. Since you need to know the exact point, you should use Physics.Raycast:
var point: Vector3;
var duration: float;
var object: GameObject;
private var startTime: float = 0;
function Update(){
if (Input.GetMouseButtonDown(0)){
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)){
startTime = Time.time;
point = hit.point;
object = hit.transform.gameObject;
}
}
else
if (Input.GetMouseButtonUp(0)){
duration = Time.time - startTime;
}
}
This script may be attached to any object (usually Main Camera or an empty object). It will measure the click duration in duration and return the point in point and the clicked object in object
The way I did is I used a ray from the mouse position to grab hit information back, then you can use an if statement like if (Input.GetMouseButtonDown(0) && mouseHit.tag == "CorrectObject"){ print("HIt The Correct Game Object"); }
– sacredgeometryP.s. is it a 3d game or a 2d/2.5d game....because the former is a lot easier to work out (as I recently found out)
– sacredgeometryRayCast is useful when you're working with Touch devices so i think you can use OnMouseDown(). If you want to check how many seconds the mouse button was held, you could use Time.time and make a substract.
– SrNullactually I think it's a 2.5d... charachter can only move in 2d space, but he himself is 3d, and his limbs move in 3d.
– canahariOnMouseDown does raycasting, so neither method is quicker--they are the same.
– Eric5h5