- Home /
Different Position (Object position - Mouse Position)
Hello everyone.
I've created a script where the user clicks the screen and Logs where the user clicked.
void Start ()
{
theGameObject = GameObject.Find ("theGameObject").GetComponent<theGameObjectController> ();
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButtonDown(1))
{
theGameObjectPosition = theGameObject.transform.position;
//Get users input position(where they shoot);
userInputPosition = Input.mousePosition;
Debug.Log (userInputPosition);
Debug.Log (playerPosition);
}
}
But the Logs are way different(clicking right in front of the object.) I get this:
(Game Object) (-0.6, 0.0, 0.0) UnityEngine.Debug:Log(Object) bulletAnimator:Update() (at Assets/FirstLevel/FirstLevelScripts/Weapon/bulletAnimator.cs:37)
(Mouse Input) (322.7, 135.5, 0.0) UnityEngine.Debug:Log(Object) bulletAnimator:Update() (at Assets/FirstLevel/FirstLevelScripts/Weapon/bulletAnimator.cs:36)
Im attaching the script to the GameObject. and My Hierarchy looks like this:
-Background
-GameObjectA
|--Main Camera-GameObjectB
Why are both positions way off? How do I fix, where do I attach the script?
The GameObject was instantiated on (0,0,0)....
Answer by ArkaneX · Mar 06, 2014 at 04:01 PM
Input.mousePosition returns screen coordinates, while transform.position returns world coordinates. You can transform between these coordinates by using Camera.WorldToScreenPoint and Camera.ScreenToWorldPoint
So the mousePosition would be like this?
userInputPosition = Camera.ScreenToWorldPoint(Input.mousePosition);
That will give you the world position but be aware that the z that's passed into that function will be 0. So it will be 0 units away from the camera and may give you undesirable results.
Exactly. If you want to get world position with a predefined z
value, then you have to create new Vector3
variable and pass it to the method:
var v = new Vector3(Input.mousePosition.x, Input.mousePosition.y, z);
userInputPosition = Camera.main.ScreenToWorldPoint(v);
Please note that I used Camera.main, which uses first enabled camera, with tag $$anonymous$$ainCamera. You can't call these methods on Camera class itself, as they are not static. You have to use specific camera instance.
Your answer
![](https://koobas.hobune.stream/wayback/20220613135533im_/https://answers.unity.com/themes/thub/images/avi.jpg)