Control a game object’s rotation and camera zoom

Introduction

This code is a Unity game development script, which is used to control the rotation of a game object and the zoom of the camera. Here are the main features of the code:

  1. Control the rotation of a game object:

    • By pressing the Q and W keys, the user can choose to rotate the game object in a counter-clockwise or clockwise direction around the Y-axis.
    • The rotation angle and speed can be adjusted through public variables, which can control the angle and speed of each rotation.
    • The rotation is smooth, using the Slerp interpolation method to ensure that the rotation process is smooth.
  2. Control the camera’s zoom:

    • Through mouse wheel input, the user can zoom in and out of the main camera in the scene.
    • The zoom range can be limited by setting minimum and maximum field of view (FOV) values.

In summary, this script allows the user to control the rotation of the game object via keystrokes, while also controlling the zoom of the main camera via the scroll wheel. This can be an interesting element for in-game interaction and user experience.

Method

using UnityEngine;

public class RotateObject : MonoBehaviour
{<!-- -->
    public float rotationAngle = 60f; // Rotation angle, specify the angle of each rotation
    public float rotationSpeed = 5.0f; // Rotation speed, control the speed of rotation
    public float zoomSpeed = 5.0f; // Zoom speed, controls the speed of camera zooming
    public float minFOV = 10.0f; // Minimum field of view, specifies the minimum field of view value of the camera
    public float maxFOV = 60.0f; //Maximum field of view, specifies the maximum field of view value of the camera

    private bool isRotating = false; // Whether the mark is rotating
    private Quaternion targetRotation; // Target rotation, used to store the quaternion of the target rotation

    private Camera mainCamera; // main camera

    void Start()
    {<!-- -->
        mainCamera = Camera.main; // Get the main camera in the scene
    }

    void Update()
    {<!-- -->
        if (Input.GetKeyDown(KeyCode.Q) & amp; & amp; !isRotating)
        {<!-- -->
            // Start rotating counterclockwise around its own Y axis
            StartRotation(false); // Call the StartRotation function to start counterclockwise rotation
        }
        else if (Input.GetKeyDown(KeyCode.W) & amp; & amp; !isRotating)
        {<!-- -->
            // Start rotating clockwise around its own Y axis
            StartRotation(true); // Call the StartRotation function to start clockwise rotation
        }

        if(isRotating)
        {<!-- -->
            // Use Slerp to rotate every frame
            float t = Time.deltaTime * rotationSpeed; // Calculate interpolation parameters based on rotation speed
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, t); // Use the Slerp function to achieve smooth rotation

            // Determine whether it is close to the target rotation
            if (Quaternion.Angle(transform.rotation, targetRotation) < 1.0f)
            {<!-- -->
                isRotating = false; // Mark the end of rotation
            }
        }

        // Handle camera zoom
        float scrollWheel = Input.GetAxis("Mouse ScrollWheel"); // Get the input value of the mouse wheel scrolling
        if (scrollWheel != 0)
        {<!-- -->
            float newFOV = mainCamera.fieldOfView - scrollWheel * zoomSpeed; // Calculate the new field of view value based on the input value
            newFOV = Mathf.Clamp(newFOV, minFOV, maxFOV); // Use the Mathf.Clamp function to ensure that the field of view value is within the specified range
            mainCamera.fieldOfView = newFOV; // Update the camera's field of view value
        }
    }

    void StartRotation(bool clockwise)
    {<!-- -->
        isRotating = true; // Marker is rotating

        // Calculate target rotation
        float angle = clockwise ? rotationAngle : -rotationAngle; //Select the rotation angle according to clockwise or counterclockwise
        targetRotation = Quaternion.Euler(0, angle, 0) * transform.rotation; // Calculate the quaternion of the target rotation
    }
}

Give examples

Of course, here’s a step-by-step explanation of what each major part of the code does:

  1. using UnityEngine;: Introduce the Unity namespace so that Unity classes and functions can be used.

  2. public class RotateObject : MonoBehaviour: Defines a public class named RotateObject, which inherits from Unity’s MonoBehaviour class, which is in Unity Base class for all scripts.

  3. public float rotationAngle = 60f;: Defines a public floating point variable rotationAngle, which is used to specify the angle of each rotation. The default value is 60 degrees.

  4. public float rotationSpeed = 5.0f;: Defines a public floating-point variable rotationSpeed, which is used to control the speed of rotation. The default value is 5.0.

  5. public float zoomSpeed = 5.0f;: Defines a public floating point variable zoomSpeed, which is used to control the speed of camera zoom. The default value is 5.0.

  6. public float minFOV = 10.0f;: Defines a public floating point variable minFOV, which is used to specify the minimum field of view value of the camera. The default value is 10.0.

  7. public float maxFOV = 60.0f;: Defines a public floating point variable maxFOV, which is used to specify the maximum field of view value of the camera. The default value is 60.0.

  8. private bool isRotating = false;: Defines a private Boolean variable isRotating, which is used to mark whether rotation is in progress. The default value is false (false).

  9. private Quaternion targetRotation;: Defines a private quaternion variable targetRotation for storing target rotation information.

  10. private Camera mainCamera;: Defines a private camera object mainCamera, which is used to reference the main camera in the scene.

  11. void Start(): This is a life cycle method that is called when the script is loaded. In this method, the script gets a reference to the main camera in the scene.

  12. void Update(): This is a life cycle method that will be called every frame. In this method, the script handles the input and controls the rotation of the object and the zoom of the camera.

  13. Enter the detection section:

  • Detect that the user pressed the Q key or W key through Input.GetKeyDown(KeyCode.Q) and Input.GetKeyDown(KeyCode.W), and isRotating When code> is false, the rotation operation is triggered.
  1. Rotation operation part:
  • When isRotating is true, Slerp interpolation is used to achieve smooth rotation so that the object rotates at the specified speed to the target rotation.
  • Determine whether the rotation is close to the target by comparing the angle between the current rotation state and the target rotation state. When the angle is less than 1.0 degrees, the end of the rotation is marked.
  1. Camera zoom operation part:
  • Detect mouse wheel input and get the value of the wheel.
  • Adjust the camera’s field of view value based on the input value, and use the Mathf.Clamp function to ensure that the field of view value is within the specified minimum and maximum range.
  1. void StartRotation(bool clockwise): Custom method for starting the rotation operation.
  • Use the clockwise parameter to decide whether to rotate clockwise or counterclockwise.
  • Calculate the target rotation angle and store it in targetRotation for use in smooth rotation operations.

These sub-sections explain the role and function of each part of the code.