- Home /
How do I flip a sprite based on parent's rotation?
I have a thing set up, that makes the gun rotate in the direction of the cursor around the player and I want to make it so, when it's past or below a certain rotation.z value, it flips the gun's sprite. This is the code I have:
using UnityEngine;
public class Shooting : MonoBehaviour
{
private Camera _mainCam;
private Vector3 _mousePos;
public SpriteRenderer gun;
public GameObject thisObj;
private void Start()
{
_mainCam = GameObject.Find("Main Camera").GetComponent<Camera>();
}
private void Update()
{
RotatePoint();
RotateGun();
}
void RotateGun()
{
if (thisObj.transform.localEulerAngles.z is < 270f or > 90f)
{
gun.flipY = true;
}
else if(thisObj.transform.localEulerAngles.z is > 270f or < 90f)
{
gun.flipY = false;
}
Debug.Log(thisObj.transform.localEulerAngles.z);
}
void RotatePoint()
{
_mousePos = _mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 rotation = _mousePos - transform.position;
float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0,0,rotZ);
}
}
And this is the hierarchy setup: I've tried using transform.rotation.z too.
Any help is much appreciated!
Answer by Linezokode · Apr 14 at 01:15 PM
Solved it. This is how:
void RotateGun()
{
var mPosToPlayer = _mousePos - gameObject.transform.position;
if (mPosToPlayer.x < 0)
gun.flipY = true;
else
gun.flipY = false;
}
Your answer
Follow this Question
Related Questions
Shooter 2D - Problem with rotation of bullet to face direction (velocity) 2 Answers
Bullet follows player mouvement when It instintiates. 1 Answer
Slow Sprite Rotation Toward Movement Direction - Top-Down 2D Game 0 Answers
Instantiate a GameObject with a specific Z rotation 2 Answers
My player is not rotating upwards when it moves upwards. Any advice? 1 Answer