- Home /
Getting GameObject's local mouse position relative to screen point
I have a GameObject of a plane in my scene. The GameObject is facing the camera upright, like in the screenshot below:
When I do a `Input.mousePosition`, I am getting the coordinates of the mouse on the screen. How can I get the mouse position that is local to the GameObject, but is still relative to the screen?
Because of how my scene is currently set up, I cannot use `GUITexture`, which has a handy `GetScreenRect()` for this purpose.
So for example, when I click on the red dot shown in the picture above, `Input.mousePosition` may give me `(450, 380, 0)`. This is the screen's point. My intention is to get a mouse position that is local to the GameObject. So in this example, suppose the GameObject has a width of `200px` and a height of `150px` on the screen. By clicking on the red dot position (the middle of the GameObject), I should get `(100, 75, 0)` as my mouse position.
How can I achieve this?
Thanks!
Answer by Muuskii · Oct 11, 2012 at 03:21 AM
Try constructing a Plane then use Camera.ScreenPointToRay to get a ray pointing along the mouse position and then use Plane.Raycast using that ray to get where the ray intersects the plane.
Make sure, when constructing the plane that it is in the same position as the GameObject and that it has the same orientation. Do this by setting the plane's normal to GameObject.Transform.Up
Edit: Your version is close but here is a few changes:
float hitdistance = 0.0f;
Ray ray = camera.ScreenPointtoRay(Input.mousePosition); //You need to keep this for later
Plane plane = new Plane(transform.up, transform.position);
if( plane.Raycast(ray, out hitdistance) ) //Naturally this should never return false. . .but, whatever
{
Vector3 hitPoint = ray.GetPoint(hitdistance);
}
You don't replace the GameObject with the plane. It's just serving as a sort of "collider" for the raycast to intersect with. Difference between Plane.Raycast and Physics.Raycast is that the former will only hit the plane. So you don't have to do any checks if a given point should be used or not.
Note: If this script is not attached to the GameObject in question; You will have to replace the transform mentioned in the code above, with the GameObject's transform.
Do I do something like this:
Plane plane = new Plane();
plane.Raycast(camera.ScreenPointtoRay(Input.mousePosition));
And I have to replace my current GameObject shown the picture in the question with the plane?
Your answer
Follow this Question
Related Questions
Mouse aims at object ? 1 Answer
Get the length from the object i click on to the mouserelease.. how? 0 Answers
AddForce at mouse position only on table area 0 Answers
Best way to hold mouse cursor on control while activated? 0 Answers
How to make input.mousePosition Vector2 centered to middle of screen? 2 Answers