I have a script where my player will follow the mouse as well as rotating to face the mouse. I want my player to only move up, down, left and right while rotating to face the cursor. Right now my code is if you press W the player moves towards the mouse, something I do not want. Any help is appreciated and I have already looked at some other forums with no luck.
var mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Quaternion rot = Quaternion.LookRotation(transform.position - mousePosition,Vector3.zero);
transform.rotation = rot;
transform.eulerAngles = new Vector3 (0,0, transform.eulerAngles.z);
var rig = GetComponent<Rigidbody2D>();
rig.angularVelocity = 0;
float inputV = Input.GetAxis("Vertical");
float inputH = Input.GetAxis("Horizontal");
rig.AddForce (gameObject.transform.up * speed * inputV);
rig.AddForce (gameObject.transform.right * speed * inputH);
Answer by inahst
Mar 13 at 08:53 AM
@UnityNoob123 Hey, how's it going? You probably have gotten this figured out a while ago but if not (and for anyone that might find this and are blown that there are no comments), here is my "Look at" method
void lookAt(Vector2 p2)
float forwardAngle = 0;
Vector2 p1 = transform.position;
float opp = p2.y - p1.y;
float adj = p2.x - p1.x;
float zRadians = Mathf.Atan((p2.y - p1.y) / (p2.x - p1.x));
if (adj < 0)
zRadians += Mathf.PI;
Quaternion q = Quaternion.Euler(0, 0, Mathf.Rad2Deg * zRadians);
transform.rotation = q;
transform.Rotate(0, 0, -forwardAngle);
ForwardAngle is the z rotation of your sprite. If your sprite is facing right it's 0, left its 90, etc..
I don't know why you have to rotate an additional 180 if adj is < 0, it's some math shit that I'm too busy to figure out atm (probably should be working instead of making this post in the first place) but I'll probably come back to it later, and potentially make a look at where you input a Vector3 axis you want to rotate around. (If that's already a thing I'd love to get a link to it, but will probably try it out myself anyways just for some practice)
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
4 People are following this question.
FindChild not working - Unity 5.5 2D
Shooting towards the mouse in a top down shooter,
Need to make grid movement more smooth
Issues w/ 2D shmup ship "lean" animations on diagonals
Player keeps bumping when walking over to another sprite