- Home /
2D topdown gun rotation problem
my gun is supposed to flip when it is anywhere between 90 and -90° the issue is it works for one side but decides that it won't work anywhere between 180 and 270° is there anything I need to change in this code to fix this issue?
{
public Camera sceneCamera;
public GameObject player;
public Rigidbody2D rb;
private Vector2 mousePosition;
private bool isFlipped = false;
void Update()
{
aim();
}
public void aim()
{
mousePosition = sceneCamera.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector2(player.transform.position.x, player.transform.position.y);
Vector2 aimDirection = mousePosition - rb.position;
float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 0f;
rb.rotation = aimAngle;
if (rb.rotation > -90.0f && rb.rotation < 90.0f && isFlipped == true)
{
transform.localScale = new Vector3(0.1f, 0.1f, 1f);
isFlipped = false;
}
else if (rb.rotation > 90.0f && rb.rotation > -89.9f && isFlipped == false)
{
transform.localScale = new Vector3(0.1f, -0.1f, 1f);
isFlipped = true;
}
}
}
Answer by Caeser_21 · Mar 21 at 08:42 AM
Ok, so i found a solution... If you remove the 'IsFlipped' bool and the 'else if' statement everything should work perfectly...
This is the working code :
{
public Camera sceneCamera;
public GameObject player;
public Rigidbody2D rb;
private Vector2 mousePosition;
private bool isFlipped = false;
void Update()
{
aim();
}
public void aim()
{
mousePosition = sceneCamera.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector2(player.transform.position.x, player.transform.position.y);
Vector2 aimDirection = mousePosition - rb.position;
float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 0f;
rb.rotation = aimAngle;
if (rb.rotation > -90.0f && rb.rotation < 90.0f)
{
transform.localScale = new Vector3(0.1f, 0.1f, 1f);
}
else
{
transform.localScale = new Vector3(0.1f, -0.1f, 1f);
}
}
}
thank you caeser I really apreciate your help, I was stuck with this for 6 hours yesterday, again thank you very much :)
Your answer
Follow this Question
Related Questions
2D impact force on instantiated sprites 0 Answers
how to shoot with joystick 0 Answers
Move player backwards when firing a gun. Unity 2D. Top Down 1 Answer
Coin System with PlayerPrefs 1 Answer
2D Top Down Shooting Problem 1 Answer