I’m using the script below to rotate an object with the mouse/touch. It works perfectly when the camera is rotated at 0,0,0. However, when I try to use it when the camera is rotated at (0, 180, 0), it doesn’t work. The problem I am having is that the object rotates backwards and is also moved towards the camera a couple of units. I have tried setting the Y position to Screen.height - pos.y but that just causes more issues. What could the issue be?
Code:
using UnityEngine;
using System.Collections;
public class Spin : MonoBehaviour {
private float baseAngle = 0.0f;
void OnMouseDown(){
Vector3 pos = Camera.main.WorldToScreenPoint (transform.position);
pos = Input.mousePosition - pos;
baseAngle = Mathf.Atan2 (pos.y, pos.x) * Mathf.Rad2Deg;
baseAngle -= Mathf.Atan2 (transform.right.y, transform.right.x) * Mathf.Rad2Deg;
}
void OnMouseDrag(){
Vector3 pos = Camera.main.WorldToScreenPoint (transform.position);
pos = Input.mousePosition - pos;
float ang = Mathf.Atan2 (pos.y, pos.x) * Mathf.Rad2Deg - baseAngle;
transform.rotation = Quaternion.AngleAxis (ang, Vector3.forward);
}
}