using UnityEngine;
using System.Collections;
public class DragRotateX : MonoBehaviour
{
public Vector3 selectedAxis = Vector3.one;
public float speed = 5;
private Quaternion originalRotation;
private float startAngle = 0;
public Vector3 tempVector;
public void Start()
{
originalRotation = this.transform.rotation;
}
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
MouseDown();
}
//This block of code should be the last 2 things in your update
if (Input.GetMouseButton(0))
{
MouseHeld();
return;
}
transform.localEulerAngles = RotateAxisToNearestSide(transform.localEulerAngles, selectedAxis);
}
Vector3 RotateAxisToNearestSide(Vector3 eulerAngles, Vector3 selectedAxis)
{
Vector3 rounded = RoundToNearest90Degree(eulerAngles);
Vector3 slerped = Vector3.Slerp(eulerAngles, rounded, Time.deltaTime * speed);
return SetSelectedAxis(eulerAngles, slerped, selectedAxis);
}
Vector3 RoundToNearest90Degree(Vector3 eulerAngles)
{
for(int i = 0; i < 3; i++)
{
eulerAngles[i] = Mathf.Round(eulerAngles[i] / 90f) * 90f;
}
return eulerAngles;
}
Vector3 SetSelectedAxis(Vector3 original, Vector3 desired, Vector3 selectedAxis)
{
for(int i = 0; i < 3; i++)
{
if(selectedAxis[i] != 0)
{
selectedAxis[i] = desired[i];
}else{
selectedAxis[i] = original[i];
}
}
return selectedAxis;
}
public void MouseDown()
{
originalRotation = this.transform.rotation;
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 vector = Input.mousePosition - screenPos;
startAngle = Mathf.Atan2(vector.y, vector.x) * Mathf.Rad2Deg;
}
public void MouseHeld()
{
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 vector = Input.mousePosition - screenPos;
float angle = Mathf.Atan2(vector.y, vector.x) * Mathf.Rad2Deg;
Quaternion newRotation = Quaternion.AngleAxis(angle - startAngle, this.transform.up);
newRotation.z = 0;
newRotation.eulerAngles = new Vector3(0, -newRotation.eulerAngles.y, 0);
this.transform.rotation = originalRotation * (newRotation);
}
}