milunax
milunax
CC#
Created by milunax on 4/20/2023 in #help
❔ Clamp on rotation depending on the side facing - Unity2D
Hi guys, i'm new to C# and I got a problem I can't solve. I'm making a 2D plateformer game and I want my player to aim with his mouse BUT I don't want it to be able to fire in the back of the character. So i'm trying to clamp the rotation of my fire point verticaly at a 180° angle. When the character is facing to the right it works just fine but when the character is facing to the left my clamp is either not rotation or is doing half the job. So i'm kinda out of ideas to solve this. Any help or suggestion would be appreciated ! Here is my code so far :
public Camera cam;
public GameObject firePoint;

private Vector3 mousePos;
private float mouseAngle;
private Vector3 firePointLookDir;

void update(){
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0f;

firePointLookDir = (mousePos - firePoint.transform.position).normalized;

if (playerMovement.facingRight)
{
mouseAngle = Mathf.Clamp(Mathf.Atan2(firePointLookDir.y, firePointLookDir.x) * Mathf.Rad2Deg, -90, 90);
}
else if (playerMovement.facingRight == false)
{
mouseAngle = Mathf.Clamp(Mathf.Atan2(firePointLookDir.y, firePointLookDir.x) * Mathf.Rad2Deg, 90, 270); // I tryied differents angles combinaisons here, the 90/270 combinaison is the one doing half the job
}

firePoint.transform.eulerAngles = new Vector3(0, 0, mouseAngle);
}
public Camera cam;
public GameObject firePoint;

private Vector3 mousePos;
private float mouseAngle;
private Vector3 firePointLookDir;

void update(){
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0f;

firePointLookDir = (mousePos - firePoint.transform.position).normalized;

if (playerMovement.facingRight)
{
mouseAngle = Mathf.Clamp(Mathf.Atan2(firePointLookDir.y, firePointLookDir.x) * Mathf.Rad2Deg, -90, 90);
}
else if (playerMovement.facingRight == false)
{
mouseAngle = Mathf.Clamp(Mathf.Atan2(firePointLookDir.y, firePointLookDir.x) * Mathf.Rad2Deg, 90, 270); // I tryied differents angles combinaisons here, the 90/270 combinaison is the one doing half the job
}

firePoint.transform.eulerAngles = new Vector3(0, 0, mouseAngle);
}
2 replies