Drag-To-Rotate works with mouse but not with touch 2020
I've tried so many things over a week to make it work but before i gave up I'm going to try my luck asking here. I'm doing a drag-to-rotate for an EARTH GLOBE. The camera will be a child to a GameObject with this script. The script works fine on dekstop but not on mobile nor touch screen dekstop. Here is the combined code, hope someone can help me out. Thanks in advance.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ObjRot : MonoBehaviour { public Transform target; public float distance = 2.0f; public float xSpeed = 20.0f; public float ySpeed = 20.0f; public float yMinLimit = -90f; public float yMaxLimit = 90f; public float distanceMin = 10f; public float distanceMax = 10f; public float smoothTime = 2f; float rotationYAxis = 0.0f; float rotationXAxis = 0.0f; float velocityX = 0.0f; float velocityY = 0.0f; public bool _isRotating; void Start() { Vector3 angles = transform.eulerAngles; rotationYAxis = angles.y; rotationXAxis = angles.x; } void LateUpdate() { if (target) { if(_isRotating) { velocityX -= xSpeed Input.GetAxis("Mouse X") distance 0.02f; velocityY -= ySpeed Input.GetAxis("Mouse Y") * 0.02f; }
rotationYAxis -= velocityX;
rotationXAxis += velocityY;
rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);
//Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
Quaternion toRotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);
Quaternion rotation = toRotation;//
transform.rotation = Quaternion.Slerp(transform.rotation, toRotation, Time.deltaTime * smoothTime);//
velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);
}
}
void OnMouseDown()
{
_isRotating = true;
}
void OnMouseUp()
{
_isRotating = false;
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}
Answer by zenixue · Sep 27, 2020 at 01:16 AM
I've found the solution, just simple change the void OnMouseDown into OnMouseDrag will do. Took me almost 3 weeks to find the solution by myself. Hope others benefited from this post. Cheers.
Your answer
Follow this Question
Related Questions
Unity 2D Touch drag specific Object 0 Answers
Touch Camera Movement and Transform Player on Touch 0 Answers
Draging an object by touch input 0 Answers
Unity Lean Touch. How to rotate 3D model around custom axis only with one finger 0 Answers
Is it possible to detect touch In a certain GUI element? 1 Answer