Unity 2D topdown bow rotation

I'm trying to implement a bow in my game that follows the direction of my mouse. There are many tutorials also showing how it is done and they are all quite the same. The issue is that the cursor has to rotate around a center which is not the game object. It is better visible in video: https://streamable.com/iyhz87 And yes, I am sure that my game object is actually not moved down to where the cursor is.

This is the code I am using:

    void FixedUpdate()
{
    Vector2 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;

    transform.rotation = Quaternion.Euler(0, 0, rotZ + offset);
}
1 Answers

To adjust the rotation of the bow in your Unity 2D game so that it follows the direction of the mouse cursor around a center that is not the game object itself, you can use the following code snippet:

void Update()
{
    Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    float angle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0, 0, angle);
}

This code snippet will rotate the bow game object to face the direction of the mouse cursor around the center of the game object.