Unity 3d Tutorial – Drag and Rotate Game Object with Touch Controls

In this tutorial we will explore how to drag you finger across the screen of your phone or tablet and have a 3D object in Unity rotate matching speed of your finger movement. This is a simple tutorial and this kind of functionalities are great for mobile games especially for character selection, unlocking different trophies, items or costumes for the game etc.

Lesson objective –

  1. Create a Drag and Rotate Objects project in Unity with C#
  2. Use Touch Phase Moved selection to check which item is active and which item to rotate in the scene
  3. Attach scripts to the main camera and to the game objects
  4. Identify the right objects using the tags element in unity

 

Video Tutorial on How to drag and Rotate Game object with Touch in unity with C# programming

 

Active Objects script

This script will be attached to the Camera in the scene.

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

public class ActivateObject : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
        {

            Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position);

            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.tag == "cube")
                {

                    var objectScript = hit.collider.GetComponent<DragAndRotateCube>();
                    objectScript.isActive = !objectScript.isActive;
                }
            }
        }
    }
}

 

Drag and Rotate Cube Script

This script is attached to the 3D cubes.

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

public class DragAndRotateCube : MonoBehaviour
{
    public bool isActive = false;
    Color activeColor = new Color();

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (isActive)
        {
            activeColor = Color.red;

            if (Input.touchCount == 1)
            {
                Touch screenTouch = Input.GetTouch(0);

                if (screenTouch.phase == TouchPhase.Moved)
                {
                    transform.Rotate(0f, screenTouch.deltaPosition.x, 0f);
                }

                if (screenTouch.phase == TouchPhase.Ended)
                {
                    isActive = false;
                }
            }
        }
        else
        {
            activeColor = Color.white;
        }

        GetComponent<MeshRenderer>().material.color = activeColor;
    }
}

 

 

 

 




Comments are closed.