I asked a similar question a day ago but didn’t come up with a solution. I apologize for asking again but it’s driving me nuts. I looked in the script manual for various ideas such as ray.GetPoint and Camera.main.ScreenToWorldPoint but they didnt help.
What I’m trying to do is check if the mouse cursor is near a prefab in the scene.
Lets say I have a Cube prefab transform.position at 0,0,4 in world space. If the mouse cursor gets near the Cubes transform.position.x or y a certain distance, then the audio gets louder or the cubes color gets brighter or whatever.
I don’t know how to get the mouse position and gameobject.transform position to be using the same coordinate system.
The cube lives in 3D world space. Your cursor lives in 2D screen space. So “get near” means you first have to calculate the distance between the camera and a plane passing through the object you are testing parallel to the plane of the camera. This distance allows you to project the mouse position into the 3D world. If you are looking down the ‘Z’ axis, then that distance will be the difference in ‘Z’ values of the two objects. Once you calculate the distance, you can use Camera.ScreenToWorldPoint() to calculate the position of the mouse. Assuming looking down the ‘Z’ axis:
var dist = Mathf.Abs(transform.position.z - Camera.manin.transform.position.z);
var v3Pos = Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
Now you can calculate the distance between the ‘cursor’ and your object:
var distanceBetween = Vector3.Distance(v3Pos, transform.position);
If your camera is moving around (i.e. not just looking down the ‘Z’ axis) for what you are doing here you can fudge the distance calculation and just use the distance between the camera and the object for distance:
var dist = Vector3.Distance(Camera.main.transform.position, transform.position);
Or if for some reason you need a more accurate distance calculation, you can approach your problem using Unity’s mathematical Plane class:
var plane = new Plane(Camera.main.transform.forward, transform.position);
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var dist : float;
if (plane.Raycast(ray, dist)) {
var v3Pos = ray.GetPoint(dist);
var distanceBetween = Vector3.Distance(v3Pos, transform.position);
}
One way would be to use Physics.SphereCast and Physics.Raycast, cast them both from the cursor position. If the SphereCast hits the object, but the Raycast doesnt’t, it means the cursor is near the GameObject. If the Raycast hits the object, the cursor is right on the object.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rayHit;
RaycastHit sphereHit;
if(Physics.Raycast(ray, out rayHit)){
//Check if rayHit.collider.gameObject is your object
//If it is, the cursor is directly on it
}
if(Physics.SphereCast(ray, 1, sphereHit)){
//Check if sphereHit.collider.gameObject is your object
//If it is, the cursor is near it
}