1
\$\begingroup\$

I'm making a 2D top-down shooter in unity. Currently, I'm using the code below to point my player towards my cursor at all times, this works but isn't exactly what I want.

//Find the mouse position on the camera view
Vector3 mousePoint = theCamera.ScreenToWorldPoint(Input.mousePosition);

//Find how the mouse relates to the object's position
Vector3 difference = mousePoint - transform.position;
difference.Normalize();

//Find wanted angle of rotation
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
Quaternion newRotation = Quaternion.Euler(new Vector3(0.0f, 0.0f, rotZ + adjustmentAngle));

//Apply wanted angle of rotation
transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, Time.deltaTime * smoothing);

While this works, my player's gun isn't in the centre of my player so when the gun fires it actually skims past the cursor missing slightly.

How can I get my player to rotate so his gun is what points towards the cursor rather than himself? I have a child GameObject at the end of the barrel of his gun used to Raycast and stuff which I figure can be used?

\$\endgroup\$
0
\$\begingroup\$

I don't believe the answer here is to make the gun point towards the cursor, but to make the gun fire towards the cursor. So keep your current rotation mechanism and instead make your GameObject fire towards the cursor.

If this looks weird (like your character is shooting really wonky) you should probably rotate the weapon to accommodate for this change. IMO it looks better than having your character look to the side of an enemy almost like he's looking into the distance.

\$\endgroup\$
  • \$\begingroup\$ Not quite, because when we rotate the player object, holding the gun object at some offset, we end up changing​ the position of the gun, so the angle we calculated based on its previous position might no longer be correct. \$\endgroup\$ – DMGregory Apr 8 '17 at 19:51
  • \$\begingroup\$ @DMGregory true, didn't think of that. Although I don't think the actual solution here is making the gun point towards the cursor, it's to use the current system but also make the gun fire towards the cursor so the real solution is probably to just change the firing mechanism. \$\endgroup\$ – Charanor Apr 8 '17 at 19:55
  • \$\begingroup\$ This also wouldn't work for if the cursor was placed in between the person and the barrel of the gun... The bullets would fly back towards the player \$\endgroup\$ – Toby Smith Apr 9 '17 at 9:17
  • \$\begingroup\$ Well of course you'd have to implement some check for that :) I can't address every little thing. \$\endgroup\$ – Charanor Apr 9 '17 at 9:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.