I am currently working on a 2d game in a top down perspective and I can’t figure out how to get bullets to shoot towards the mouse. I’ve done the obvious of translating screen position to world position but any method I use to rotate the bullets transform.rotate isn’t doing anything. I’ve been looking up information on Quaternions, EulerAngles and Vector3 rotation but I’ve come up with nothing so far.
Think twin stick shooter but with wasd (or arrow keys) as movement and the mouse is the direction the player shoots. Any help would be much appreciated, I’ve been at this for a long time now.
Try looking at the sample project Angry bots, that is given with Unity. I think you will find what you’re looking for in there.
‘Top Down’ to me means the camera looking down the ‘Y’ axis onto the XZ plane. This appears to be a standard view with the camera looking towards positive ‘Z’ onto the XY plane. One problem that may be what is causing your issues is on line 5. The ‘Z’ parameter is the distance in front of the camera, not the position of your object. Assuming your 2D plane has a ‘z’ of 0.0, and the setup is as I assume, you can just negate the value:
Vector3 direction = Camera.main.ScreenToWorldPoint
(new Vector3(x, y, -Camera.main.transform.position.z)) - myPos;
If the 2D plane has a ‘Z’ position other than 0.0, you can do:
Calculate the position of the ‘Z’ by:
float dist = transform.position - Camera.main.transform.position.z;
Note if the distance from the camera to the 2D plane remains constant, you can do either calculation in Start().
Also when you do the look rotation, you likely want to specify the optional second (up) parameter. Given a 2D game with the camera looking forward, you want to use Vector3.forward for this prameter.
Quaternion.LookRotation(direction, Vector3.forward);