MyRotationTouchpad script for Unity3D



This script is made for you if you need a touch pad feature in your Unity game or app.

Let’s say you want to rotate an object left or right by clicking and dragging the screen to the same direction (left or right), then this script may be useful to you.

Here is the script:

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

public class MyRotationTouchpad : MonoBehaviour
{

    public Transform Rotatable;
    public float RotationSpeed = 1;

    bool ismouseheld;
    Vector2 currentMousePosition;
    Vector2 mouseDeltaPosition;
    Vector2 lastMousePosition;
    bool istouchpadactive;

    private void Start()
    {
        currentMousePosition = Input.mousePosition;
        lastMousePosition = currentMousePosition;
        mouseDeltaPosition = currentMousePosition - lastMousePosition;
    }

    void Update()
    {
        if (istouchpadactive) {

            currentMousePosition = Input.mousePosition;
            mouseDeltaPosition = currentMousePosition - lastMousePosition;

            Rotatable.transform.Rotate(0f, mouseDeltaPosition.x * RotationSpeed, 0f);

            lastMousePosition = currentMousePosition;
        }
    }

    public void ActivateTouchpad()
    {
        istouchpadactive = true;
    }

    public void DeactivateTouchpad()
    {
        istouchpadactive = false;
    }
}

I’ve made a video tutorial to show you how exactly we can use this script.

loading...

Leave a Reply

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