- Home /
Get Local Mouse Position from the center of the Gameobject clicked on
I want to get the mouse clicked position from the center of the gameobject, say a Sphere of Scale(1, 1, 1), for instance. If I click on the center of the sphere it should return the x component as zero, on clicking to the extreme left of the sphere, it should return -0.5 as the x component of the vector3 and 0.5 on clicking the extreme right of the sphere. The below code helps me achieve this. However, there is one constraint for it. The Sphere has to be positioned at (0, anything, anything) (as I am concerned with the x axis). Any help on how can I achieve this regardless of the Sphere position?
bool isGameOver = false;
float pointX;
// Update is called once per frame
void Update () {
if(!isGameOver){
RaycastHit hit;
if(Input.GetMouseButtonDown(0)){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit)){
if(hit.transform.tag =="Ball"){
pointX = transform.InverseTransformPoint(hit.point).x;
}
}
}
}
}
EDIT: I am using Perspective camera, it works fine for Orthographic view of a camera
Hi,
i tried ur code and i positioned a cube at random positions where x != 0 and it gaves me the correct cords for x between -0.5 und 0.5 relative to the center point of the cube.
Did i understand something wrong?
Hi, If I position it, say x=2. And I click on the center of the sphere, it doesn't give me 0. It gives me -0.15 kind of values.
@Chris333.. I am using Perspective camera, it works fine for Orthographic view of a camera
Did you assigned the script to the sphere and not to the camera?
Iam using perspective too.
Answer by Chris333 · Apr 27, 2015 at 05:39 PM
I tried it now with a sphere and it looks a like that it has something to do with the rotation. I get different values if i rotate the sphere.
Can you trie that instead of InverseTransformPoint().x
if(hit.transform.tag =="Ball"){
//pointX = transform.InverseTransformPoint(hit.point).x;
Debug.Log (transform.position.x - hit.point.x);
}
Answer by fafase · Apr 27, 2015 at 07:30 PM
InverseTransformPoint converts a world point to a local point so obviously the rotation will affect the result.
If you are facing me and I throw a ball at you, you will get it at (0,0,1), now if you turn 90 degrees and I throw again, I will hit you at (1,0,0). Even though the position in the world space is the same, in your own system it has changed.
So your solution is indeed to remain in world space with some basic vector arithmetic as shown above.