- Home /
Having Problem with mouseposition.
I want to show an object at the mouse position. But the object is moving relatively to the mouse but in a shifted position. I'm using
transform.position = Input.mousePosition;
I want to show the object exactly at mouse position.
also, is this a 2d or 3d game? if 3d, you may want to look at raycasting
Answer by Proximal-Pyro · Nov 17, 2014 at 10:10 AM
Hi!
Input.mousePosition is calculated in pixels (The same way you would use the old GUI). I suggest doing something like:
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if this does not work i suggest trying to raycast. You can probably look around on google for a bit and find something about this.
//Proximal Pyro
the code works, but the object's z coordinate becomes equal to the camera's z coordinate and it disappears from the game window. Any suggestions to that?
you can add a constraint
float zPos = 20f; // or whatever you want to constrain it to
//in function
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(transform.position.x, transform.position.y, zPos); // this line will alter the z to match the zPos variable
Answer by Wisearn · Nov 17, 2014 at 09:46 AM
Input.mousePosition will give you numbers that are 1 per pixel for screen width and screen height (like 1280 x 720).
It has nothing to do with a transform.position which is 1 per unit in your world scene.
As @bubzy mentioned if it's a 3d game you will want to do a http://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html
If it's 2d you can get away with a cheaper: http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
Lightning Script Js To C# Conversion errors 2 Answers
Enter spoken words in game 1 Answer
BCE0044: expecting EOF, found '}'. 1 Answer