/

22/05/2024

How to Rotate an Object Using One Finger in Unity

Introduction:

At Omitram, we specialize in creating engaging and interactive mobile and AR/VR applications. One of the key features often needed in these applications is the ability to rotate objects using touch input. In this tutorial, our expert developers will guide you through the process of rotating a 3D object in Unity using a single finger on a touchscreen device.

Prerequisites:
    • Unity Hub installed.
    • Unity Editor (version 2020.3 or later).
    • Basic understanding of C#.
    • Mobile device for testing (optional).
Step-by-Step Guide:

1. Setting Up the Scene:

    • Open Unity and create a new project.
    • Create a 3D object (e.g., cube or sphere) in the scene.
    • Position the Camera to face the object.

2. Creating the Script:

    • In the Project window, right-click and select Create > C# Script. Name it RotateObject.
    • Open ‘RotateObject.cs‘ in your code editor.

3. Writing the Script:

Replace the contents of ‘RotateObject.cs‘ with:

using UnityEngine;

public class RotateObject : MonoBehaviour
{
public float rotationSpeed=100.0f;
public bool VerticalRotation = true;
public bool HorizontalRotation = true;
 
private void Update()
{
// Check if there is at least one touch
if (Input.touchCount>0)
{
Touchtouch=Input.GetTouch(0);
// Check the touch phase
if (touch.phase==TouchPhase.Moved)
{
// Apply rotation to the object
if(HorizontalRotation)
{
float rotationY=-touch.deltaPosition.x*rotationSpeed*Time.deltaTime;
transform.Rotate(Vector3.up, rotationY, Space.World);
}
if(VerticalRotation)
{
float rotationX=touch.deltaPosition.y*rotationSpeed*Time.deltaTime;
transform.Rotate(Vector3.right, rotationX, Space.World);
}
}
}
}
}

4. Applying the Script:

      • Attach the script to the 3D object by dragging it onto the object in the Hierarchy window.
      • Adjust the rotation speed in the Inspector window if needed.

5. Testing the Application:

      • Build and run the application on a mobile device.
      • Use one finger to swipe on the screen. The object should rotate accordingly.

Download Unity Package