Hi,
I’ve been looking around and all of the answers I found for this subject do not exactly fit my problem.
My project has a top-down 2D view on space ships.
I’m making my own simple AI for an enemy space ship.
Once the player is within a fixed range, the enemy does 3 things:
- Rotate towards the player, to face it.
- Fly towards the player, or back off, to maintain a certain distance.
- Shoot at the player if the enemy is facing it.
Currently I have a problem with the 1st behavior.
Different Ships have different thrusters and so rotate left or right at a different speed.
This is why Transform.LookAt() doesn’t fit here.
I’ve seen an almost perfect solution using PlayerPosition - EnemyPosition vector, then run it’s Y and X components thorugh Atan2.
The problem with this is observed here:
excellentmessyantelope
In the negative X and negative Y quarter of the axis system, there is a gap or a shift between 90 degrees and -270 degrees.
Right when the player crosses to that quarter, this jump from 90 to -270 causes the enemy to rotate in the wrong direction, taking the longer way to face the player.
I’m using this code:
Vector2 DirectionToPlayer = PlayerShip.transform.position - transform.position;
DirectionToPlayer.Normalize();
float AngleToPlayerShip = Mathf.Atan2(DirectionToPlayer.y, DirectionToPlayer.x) * Mathf.Rad2Deg - 90;
if (NPCBody.rotation - AngleToPlayerShip > 5)
{
ShipToControl.RotateRight();
}
else if..
{
ShipToControl.RotateLeft();
}
Is there a way to get the rotation angle in a consecutive manner throughout all quarters of the axis system?
Or, alternatively, replacing NPCBody.rotation to something else that follows this pattern?
This function is located inside the Update function of the Enemy AI Script.
Note: The -90 in the angle is not the issue, I removed it and the same thing happend but in 180 degrees instead of 90.