Rotation in wrong direction
This is my code for rotation of an object towards another object. It works just as I need except that sometimes the object rotates towards the target in wrong direction.
I have a ship that rotates itself towards destination. Lets say the destination is on its right. Normally the ship would rotate by (for example) 30 degrees to the right, so it faces the destination. But when it is hit by a bullet, it sometimes rotates by 330 degrees to the left until it faces the destination (instead of rotating 30 degrees to the right).
The hit and speed reduction is processed through box colliders that are placed on both the ship and the bullet. Bullet is the trigger and it calls the method OnTriggerEnter2D that than calls a method inside the ship that starts a coroutine slowing the ship.
Here is the Ships code for movement:
Vector2 direction = (targetCheckPoint.position - transform.position).normalized;
Quaternion rotation =transform.rotation * Quaternion.FromToRotation(transform.up, direction);
rb.SetRotation(Quaternion.RotateTowards(transform.rotation, rotation, actualRotSpeed * Time.fixedDeltaTime));
rb.velocity = (transform.up * (movementSpeed + speedChange));
Here is the code for the bullet hit:
private void OnTriggerEnter2D(Collider2D collision)
{
Enemy e = collision.gameObject.GetComponent<Enemy>();
if(e!= null)
{
if (e.isSpeedChangeAllowed && speedChangeMultiplier > 0f)
{
e.changeSpeed(speedChangeMultiplier);
}
e.takeDamage(damage);
Destroy(gameObject);
}
}
If any additional information is required, please let me know.