Skip to content

Instantly share code, notes, and snippets.

@rje
Created May 2, 2014 04:09
Show Gist options
  • Save rje/864e4f8010301324f4f8 to your computer and use it in GitHub Desktop.
Save rje/864e4f8010301324f4f8 to your computer and use it in GitHub Desktop.
Rotation Script
using UnityEngine;
using System.Collections;
public class RotateObject : MonoBehaviour {
public float RotationPerPixelMovement = 1.0f;
GameObject _toRotate;
bool _rotating = false;
Vector3 _lastPosition;
Vector3 _objEulerAngles;
void Update()
{
CheckForActivation();
HandleRotation();
}
void CheckForActivation()
{
if (Input.GetMouseButtonDown(0) && FindObjectUnderCursor())
{
_lastPosition = Input.mousePosition;
_objEulerAngles = _toRotate.transform.rotation.eulerAngles;
_rotating = true;
}
else if (Input.GetMouseButtonUp(0))
{
_rotating = false;
}
}
bool FindObjectUnderCursor()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rh;
if (Physics.Raycast(ray, out rh, float.MaxValue))
{
_toRotate = rh.collider.gameObject;
return true;
}
return false;
}
void HandleRotation()
{
if(!_rotating)
{
return;
}
var pos = Input.mousePosition;
var delta = pos - _lastPosition;
_lastPosition = pos;
_objEulerAngles.x += delta.y * RotationPerPixelMovement;
_objEulerAngles.y -= delta.x * RotationPerPixelMovement;
_toRotate.transform.rotation = Quaternion.Euler(_objEulerAngles);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment