2D Enemy spins while aiming
I am quite a noob in Unity and just started learning. I managed to rotate the bullets coming from the enemy to point in the direction of the player. When I try to use the same, slightly changed, code, to manage the variable names, and put it into the "Update" function, it spins continuously. In the "start" function it works just fine and rotates the enemy to look at the player when the game is started. This is the code:
public GameObject shooter;
PlayerController target;
Vector2 aimInDirection;
void Update()
{
ShooterAiming();
}
private void ShooterAiming()
{
target = GameObject.FindObjectOfType<PlayerController>();
aimInDirection = (target.transform.position - transform.position).normalized;
shooter.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(aimInDirection.y, aimInDirection.x) * Mathf.Rad2Deg);
}
Hope someone can help me
Answer by Dsiak · Nov 25, 2021 at 12:36 AM
".Rotate" is a function that rotates the object by the given degrees, it's not meant to set the rotation to a given degree. So lets suppose you start your game and the enemy needs to rotate 10 degrees to face the player, it will rotate 10 degrees on the first frame and them another 10 on the second and another 10 on the third and so on. What you actually need is to set the rotation to be the direction. Try this transform.up = aimInDirection
or even better, try Lerping the value to get a smooth transition transform.up = Vector3.Lerp(transform.up, aimInDirection, Time.deltaTime * turnSpeed);