I'm making a 2D top-down shooter for the PC using C#. I've rotated my camera by 90 degrees along the X axis so I can use transform.LookAt constraint to look at the position of the mouse but something puzzles me. Here's the code I got down which gives the desirable effect.
//Look at mouse position Vector3 MousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0)); MousePosition.y = 0; transform.LookAt(MousePosition);
This code however doesn't
//Look at mouse position Vector3 MousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, 0, 0)); transform.LookAt(MousePosition);
Why can't I immediately set the MousePosition.y to 0? When I move my mouse around the gameobject to which this script is attached seems to target a position on the same y position of the camera. There's probably a neater way to code this but I am clueless as to how (using c#).
asked Jan 27, 2011 at 12:20 AM
Having a look at it again, I found out that the z value of MousePosition needed to be changed from 0 to Camera.mainCamera.farClipPlane or increasing it to 10 (which was the height at which I positioned the camera and also the value of the far clip plane).
Since the all the values are camera relative putting a 0 value for z made it always aim at the camera's z position.
May I ask what you're trying to achieve? Also, it may be related to a problem that I had before; Note that when using ScreenToWorldPoint, the y value the 0 is not the top of the screen, but the bottom of the screen. So if you were expecting to shoot at the top of the screen, you have to provide the Screen.height rather than 0.
answered Jan 27, 2011 at 12:26 AM