I've changed the pivot point of my gun by adding a parental object for the pivot point and the child object for the gun sprite, and my gun is now turning around my player.
public class Gun : MonoBehaviour
{
private Rigidbody2D rb;
public Camera cam;
Vector2 mousePos;
Vector2 lookDir;
private float angle;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
lookDir = mousePos - rb.position;
angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
rb.rotation = angle;
}
void Update()
{
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}}
but I have no idea how to acces child object's SpriteRenderer and flipY if gun's rotation is more than -90 and less than 90.
CodePudding user response:
Simply store a reference to the SpriteRenderer
either in the Inspector
// Drag your child object into the according slot via the Inspector within Unity
[SerializeField] private SpriteRenderer spriteRenderer;
or using GetComponentInChildren
private void Awake ()
{
if(! spriteRenderer) spriteRenderer = GetComponentInChildren<SpriteRenderer>();
}
void FixedUpdate()
{
lookDir = mousePos - rb.position;
angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
rb.rotation = angle;
spriteRenderer.flipY = -90 < angle && angle < 90;
}