- Home /
LookAt and fire at mouse position
Hi,
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);
//Firing Lazers
if (Input.GetMouseButtonDown(0))
Instantiate(Lazers, transform.position, transform.rotation);
This code however doesn't
//Look at mouse position Vector3 MousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, 0, 0)); transform.LookAt(MousePosition);
//Firing Lazers
if (Input.GetMouseButtonDown(0))
Instantiate(Lazers, transform.position, transform.rotation);
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#).
Answer by PolyPanda · Jan 27, 2011 at 01:22 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.
Answer by kennypu · Jan 27, 2011 at 12:26 AM
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.
I'm trying to get a gameobject that's positioned at a height of 0 to fire other gameobjects at the position of my mouse while remaining same y value. The top code does that but any other form of LookAt code tilts the gameobject around its X axis to face the camera's height
Your answer
Follow this Question
Related Questions
Rotating a 3D object on the Y axis relative to the cursor's position? 2 Answers
Shooting bullet towards mouseposition 2D. 2 Answers
replace mouse position with right joystick direction -1 Answers
Mega Bug In Turret - Help 5 Answers
Simple LookAt follow script 1 Answer