How to rotate object in Unity 3D

Hello programmers, In this article, I will show “how to rotate object in Unity3D”.

Before we get started with the building process, we need to know a few concepts. Let’s first discuss them one by one.

transform.Rotate()

transform.Rotate() is used to rotate GameObject in a different direction. You can specify the rotation in the world axis or local axis.

When you start rotating the GameObject, the x, y, and z of the world axis get aligned with the x,y, and z of the GameObject.

Syntax:-

transform.Rotate()

OnMouseDrag() in Unity 3D

OnMouseDrag() is used when the user clicks on GameObject and still holding down the mouse.

OnMouseDrag() is called every frame while you hold down the mouse. After mouse is released even OnMouseDrag is released.

Syntax:-

void OnMouseDrag()

The below-given program is to rotate object in Unity3D :-

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Example : MonoBehaviour
{
    float rotationSpeed = 4f;

    void OnMouseDrag()
    {
        float XaxisRotation = Input.GetAxis("Mouse X") * rotationSpeed;
        float YaxisRotation = Input.GetAxis("Mouse Y") * rotationSpeed;

        transform.Rotate(Vector3.down, XaxisRotation);
        transform.Rotate(Vector3.right, YaxisRotation);
    }
}

Output:-

Below you can see the output video of our Unity program:

Leave a Reply

Your email address will not be published. Required fields are marked *