Hi, I’am having some troubles with rotating. In my Game the Character has a child GameObject, it’s gun. It’s a top down 2D shooter and I want to shoot and aim with the mouse. I got the aiming working but when rotating the gun it rotates in a big circle and when the mouse is down for example the gun is 2 units away from the Character. I want the exact same feeling of the gun rotating if I would use the rotate tool where it rotates just around the center of the object and doesn’t change its position visually, but only in code of course. I think the tricky bit comes to following the mouse angle but maybe someone someone knows how to fix it, ChatGPT is useless as hell in unity as usual.
— I am a idiot sorry. I just realized that because of the Sprites I drew everything was positioned to high and thats why the big radius when rotating. —
Here is my current code for rotating the gun to look at the Cursor:
void LookAtMouse()
{
// Get the mouse position in screen coordinates
mousePosition = Input.mousePosition;
// Screen coordinates to world coordinates
mouseWorldPosition = mainCamera.ScreenToWorldPoint(new Vector2(mousePosition.x, mousePosition.y));
// Direction from the gun to the mouse position
direction = mouseWorldPosition - transform.position;
// Angle between the gun's current forward direction and the direction to the mouse position
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
// Rotate the gun to face the mouse position
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
And this how it looks when my cursor is under the character:
Cheers