- Home /
Problem with angles and rotations in a 2D top down space shooter
Hello everyone. I'd like to start by saying that im very new to both unity and c#, so my question might be really really dumb. Im also pretty awful at math so that doesnt help with the "angle problem" I got.
Basically, Im trying to make a enemy turret slowly rotate towards the player. Since I want the rotation to be slow, Im using transform.Rotate instead of transform.rotation, as I dont know a way to make the second one be slow and not instant.
My logic is: I calculate the angle between the player ship and the enemy turret, and then I transform.Rotate the turret accordingly till the 2 angles are the same , so the turret is aiming at the player. Here's how I get the angle between the player ship and the player :
 float AngleBetweenPoints(Vector2 a, Vector2 b)
 {
     return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
 }
this returns a float that goes from 180 to -180. now, the issue starts here. in my script to rotate the turret, I check the "transform.eulerAngles.z ", that would work but the turret angle goes from 0 to 360, while the AngleBetweenPoints goes from 180 to -180 as I said. so when I use this script (attached to the turret) it works aslong and the AngleBetweenPoints is POSITIVE, but it goes bananas when the AngleBetweenPoints is negative...
void RotateTurret() {
     if (transform.eulerAngles.z < (angle ))
     {
         transform.Rotate(0, 0, 75 * (Time.deltaTime ));
     }
     if (transform.eulerAngles.z > (angle))
     {
         transform.Rotate(0, 0, -75 * (Time.deltaTime ));
     }
 }
as you can see i check the transform.eulerAngles.z of the turret and i compare it with the angle ( that is the angle between the ship and the turret) and then I use transform.Rotate and multiply by time.deltaTime to slow down the rotation.
As I said, it works till the angle is positive, but when it goes from 0 to -180 it fucks up the script. Ideally, I'd want to either convert the angle between points to a float that goes from 0 to 360, or convert the turret angle to a float that goes from 180 to -180. as I already said Im pretty crap at math, and even if I worked on this most of the night and morning I cannot find a way out. if you have any solution regarding the angle problem, or know any simpler way to accommplish what Im trying to do, please help me, Im miserable.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                