- Home /
Problem with ScreenToWorldPoint(Input.mousePosition)
I'm making a 2d game and one mechanic is that the "player" which is just a square sprite is moved by clicking on a point on the screen. The player is then moved to that spot. No fancy moving animations just teleported to that spot. Here is my script.
void Update ()
{
if (Input.GetMouseButton(0))
{
this.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
I have my main camera background as white as a skybox so the player is just a black square with a white background. When I click on a spot on the screen, the player moves to the correct spot and you can see that in the scene view but in the game view, the player dissapears. Almost like it's put behind the background skybox of the camera. Can someone please help, thanks.
Answer by sparkzbarca · Aug 30, 2016 at 03:49 AM
the issue is your mouse on the screen is a 2d thing and the world is 3d.
your mouse can go up and down and left and right on the screen but it can never go "into" or "out of" the screen, it has a depth of zero.
As such when converting from mouse to 3d you have to determine the depth yourself.
in this case normally you'd simply copy the existing Z axis so it'd be
transform.position = new vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y, transform.position.z);
thats not ideal, you should create a single instance of a vector3 and keep reassigning it instead of creating new variables each time probably and probably variable Camera.main.ScreenToWorldPoint(Input.mousePosition) just for readability.
Don't call Camera.main.ScreenToWorldPoint(Input.mousePosition) multiple times if possible. Ins$$anonymous$$d do something like this
Vector3 _mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(_mousePos.x, _mousePos.y, transform.position.z);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Objects will not spawn in a 2d game. 0 Answers
2D Flashlight for a platformer 2 Answers
Unity Look at Mouse Position 2D C# 3 Answers