Previously I’ve shared a script with you I called “MyRotationTouchpad”. But I was thinking I need to improve it.
So here it is, newer updated script. What I improved in this script is: You can rotate objects horizontally and also vertically.
This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyRotationTouchpad : MonoBehaviour
{
public Transform RotatableH;
public Transform RotatableV;
public float RotationSpeed = .1f;
public bool InvertedV = true;
public bool LimitedV = true;
bool ismouseheld;
Vector2 currentMousePosition;
Vector2 mouseDeltaPosition;
Vector2 lastMousePosition;
bool istouchpadactive;
private void Start()
{
ResetMousePosition();
}
public void ResetMousePosition()
{
currentMousePosition = Input.mousePosition;
lastMousePosition = currentMousePosition;
mouseDeltaPosition = currentMousePosition - lastMousePosition;
}
void FixedUpdate()
{
if (istouchpadactive)
{
currentMousePosition = Input.mousePosition;
mouseDeltaPosition = currentMousePosition - lastMousePosition;
if (RotatableH != null)
RotatableH.transform.Rotate(0f, mouseDeltaPosition.x * RotationSpeed, 0f);
if (RotatableV != null)
{
if (LimitedV)
{
if (RotatableV.transform.localRotation.eulerAngles.x < 45 && RotatableV.transform.localRotation.eulerAngles.x >= 0 || RotatableV.transform.localRotation.eulerAngles.x > 315 && RotatableV.transform.localRotation.eulerAngles.x <= 360)
{
if (InvertedV)
RotatableV.transform.Rotate(Mathf.Clamp(mouseDeltaPosition.y * (RotationSpeed * -1), -3, 3), 0f, 0f);
else
RotatableV.transform.Rotate(Mathf.Clamp(mouseDeltaPosition.y * RotationSpeed, -3, 3), 0f, 0f);
}
if(RotatableV.transform.localRotation.eulerAngles.x > 45 && RotatableV.transform.localRotation.eulerAngles.x < 315){
if(RotatableV.transform.localRotation.eulerAngles.x < 180){
RotatableV.transform.Rotate(-1f, 0f, 0f);
}else{
RotatableV.transform.Rotate(1f, 0f, 0f);
}
}
//Debug.Log(RotatableV.transform.localRotation.eulerAngles.x);
}
else
{
if (InvertedV)
RotatableV.transform.Rotate(Mathf.Clamp(mouseDeltaPosition.y * (RotationSpeed * -1), -3, 3), 0f, 0f);
else
RotatableV.transform.Rotate(Mathf.Clamp(mouseDeltaPosition.y * RotationSpeed, -3, 3), 0f, 0f);
}
}
lastMousePosition = currentMousePosition;
}
}
public void ActivateTouchpad()
{
ResetMousePosition();
istouchpadactive = true;
}
public void DeactivateTouchpad()
{
istouchpadactive = false;
}
}
Important Note: On line 47 if you found && please change it to && in Unity. I don’t know why WordPress is converting that symbol that way.
Update: Just download this package, it’s far more better than copying and pasting the code. Here is the link: https://drive.google.com/open?id=1u3t728OfuwaWQcpm4KRDEaZZikD31XxR
Here is the tutorial video for this topic: