Rotation is crucial for ensuring that the seagulls follow their waypoints smoothly. Letโ€™s see how we can rotate them based on their position relative to the waypoint or the player ๐Ÿ‘€.

private void RotateTowardsWaypoint()
{
    if (activeStats.isChasingPlayer && GameManager.s_player != null)
    {
        Transform activePlayerRef = GameManager.s_player.transform;

        // Increase turn speed based on distance to player ๐Ÿ“
        acceleratedRotation = Vector3.Distance(transform.position, activePlayerRef.position) / 1.2f;

        // Get the direction to the player
        Vector2 direction = (Vector2)activePlayerRef.position - rb.position;
        direction.Normalize();

        // Rotate towards the player based on cross product of direction and up vector ๐Ÿ”„
        float rotatAmount = Vector3.Cross(direction, transform.up).z;
        rb.angularVelocity = -rotatAmount * ((activeStats.rotateSpeed + acceleratedRotation) * fleeingRotatingSpeed);
    }
    else if (!activeStats.isChasingPlayer && currentWaypoint != null)
    {
        acceleratedRotation = 0;
        Vector2 direction = (Vector2)currentWaypoint.ReturnActiveWaypointTransform().position - rb.position;
        direction.Normalize();
        float rotatAmount = Vector3.Cross(direction, transform.up).z;
        rb.angularVelocity = -rotatAmount * (activeStats.rotateSpeed * fleeingRotatingSpeed);
    }
}

What the Code Does:

  • acceleratedRotation: This variable is used to increase the rotation speed based on the distance to the player. The further the player, the faster the seagull rotates.

  • Vector3.Cross(direction, transform.up).z:

    • The cross product calculates the perpendicular vector to the two input vectors (direction and up vector).

    • Why the cross product? The result tells us the direction (clockwise or counterclockwise) in which the seagull needs to rotate in order to align itself with the target. Itโ€™s essential for smooth, natural rotation. The .z component is taken since weโ€™re working in 2D and only need the rotational value around the Z-axis.

  • rb.angularVelocity: This applies the rotational speed to the Rigidbody2D based on the calculated rotation amount.

Key Concept:

The cross product gives us the direction in which to rotate (clockwise or counterclockwise). By adjusting the angularVelocity, we can rotate the seagull smoothly towards the waypoint or player. ๐Ÿ”„