0

I new to unity / c# and need some help with the rotation of my player. While I hold the mouse cursor on the positive y-axis (if the middle of the player is 0) the player faces slightly above the cursor and while on the negative y-axis the player faces slightly below the cursor. Here is a gif to demonstrate:
https://gyazo.com/e417962c20e186f3c6419c23bf8263f6

Here is my code for rotation.

public class LookTowardMouse : MonoBehaviour 
{
    void Update()
    {
        //Get the Screen positions of the object
        Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);

        //Get the Screen position of the mouse
        Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);

        //Get the angle between the points
        float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen);

        //Rotate player

        Debug.Log(angle);
        transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
    }

    float AngleBetweenTwoPoints(Vector3 a, Vector3 b)
    {
        return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
    } 
}
maccettura
  • 9,653
  • 3
  • 20
  • 28
Defty
  • 1
  • Kind of looks like because your "Character" isn't in the exact middle of the screen it is over and under compensating... I bet if you character was in the exact middle of the screen the aiming would work right. I don't code unity so I can't really provide an answer, but to the untrained eye that's what it looks like might be your problem. Can you try again with the character being in the exact middle of the screen? if it works in that case, you need to add an offset to position on screen maybe? – Kyle Bachmann Sep 10 '18 at 22:08
  • I tried placing the character in the middle of the screen with no luck. Thank you for the input though. – Defty Sep 11 '18 at 06:21
  • I misunderstood your problem. Since when a.x=b.y your canonball seems to be aligned I would say that you should check that positionOnScreen is really the center of rotation of your canonball it seems to be off by an x offset. maybe you could try setting the center of rotation. – PilouPili Sep 11 '18 at 08:56

0 Answers0