- Home /
2D Shoot at Mouse Position; how to rotate towards the mouse?
I am trying to create the shooting mechanic for a 2D topdown shooter. I need to shoot bullets at the location of the mouse. I have the code working which instantiates the bullets and shoots them in different directions based on the mouse, but the problem is that Input.mousePosition uses pixel coordinates that are not based on the position of the camera or player. By this, I mean that the bullets only shoot as they should when my character stands on (0, 0) of the pixel coordinates.
var mousePos: Vector2 = Input.mousePosition;
var bulletClone : Rigidbody2D = Instantiate(bullet, transform.position, transform.rotation);
bulletClone.rigidbody2D.AddForce(mousePos);
Also, I do not know how to rotate the bullets to the face the mouse. If I was able to do that, it would be very easy to move the bullets towards the mouse. If anyone can help me with this predicament, I would be very very appreciative. Thank you kindly!
Answer by robertbu · Jun 24, 2014 at 06:55 AM
Here is a solution. I'm assuming the camera is Orthographic. It uses Camera.ScreenToWorldPoint() for the conversion, and it use Mathf.Atan2() to generate the rotation. Note this code assumes that your object is a sprite and that the 'forward' of the bullet is facing right when the rotation is (0,0,0):
var mousePos: Vector2 = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
var dir = mousePos - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
var bulletClone : Rigidbody2D = Instantiate(bullet, transform.position, transform.rotation);
bulletClone.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
bulletClone.AddForce(bulletClone.forward * amount);
I am not sure if my long response registered, as it is not appearing here, but this worked perfectly and I CANNOT thank you enough(I got my other problem resolved as well that I had put in the orginal response). I spent 5 and half hours trying to figure this out, and I was able to simply place your code into my project. I know that you are very active on this site, so thank you again for helping everyone out!
Your answer
Follow this Question
Related Questions
Top down shooter, bullet movement issues 3 Answers
2D Tanks Shooting in right direction 0 Answers
add force on topdown bullet 1 Answer
topdown shooter unity 2 Answers
on trigger in top down shooter 0 Answers