Hi, I’ve been trying to figure out how to get this to work but haven’t been able to. I’m making a top down shooter and previously had an issue where setting the rotation point of the gun at the position of the gun itself (more precisely the barrel of the gun) would cause the gun to rotate backwards if the mouse was behind it, as you can see here:
This was fixed by moving the rotation point from the gun to the player. The issue with that is that there is now an offset as to where the cursor is and where the barrel of the gun is rotated towards.
This is the current code I’m using to rotate the gun:
using System;
using UnityEngine;
public class GunRotation : MonoBehaviour
{
public Transform Center;
private Vector3 mousePos;
private Transform player;
[NonSerialized] public SpriteRenderer spriteRenderer;
private void Start()
{
player = FindObjectOfType<PlayerMarker>().GetComponent<Transform>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
private void LateUpdate()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
CenterPosition();
RotateWeapon();
}
private void RotateWeapon()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0f;
Vector3 lookDirection = (mousePos - Center.position).normalized;
float angle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;
Debug.Log("Angle: " + angle);
transform.rotation = Quaternion.Euler(0, 0, angle);
}
private void CenterPosition()
{
Center.transform.position = new Vector2(player.transform.position.x, player.transform.position.y);
}
}