Skip to content

Instantly share code, notes, and snippets.

@but80
Last active January 16, 2020 13:22
Show Gist options
  • Save but80/465593fbace28b734d4753762bc44ebd to your computer and use it in GitHub Desktop.
Save but80/465593fbace28b734d4753762bc44ebd to your computer and use it in GitHub Desktop.
マウスで回転するやつ(1. EventSystemをヒエラルキーに追加 / 2. このコンポーネントを回転したいオブジェクトにアタッチ / 3. 同オブジェクトにIsTriggerなコライダーをアタッチ)
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// Rotates the GameObject by mouse drag.
/// The X and Y axes correspond to yaw and pitch.
/// Requires a collider attached on the same object and an EventSystem in the hierarchy.
/// </summary>
public class MouseRotator : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler
{
public Transform Camera;
public float Speed = 720f;
public float CtrlMultiplier = 4f;
public float AltMultiplier = 0.25f;
Quaternion InitialRotation;
bool IsMouseDown = false;
Vector3 LastMousePos;
void Start()
{
InitialRotation = transform.localRotation;
}
public void OnPointerClick(PointerEventData e)
{
if (e.clickCount == 2) transform.localRotation = InitialRotation;
}
public void OnPointerDown(PointerEventData e)
{
LastMousePos = Input.mousePosition;
IsMouseDown = true;
}
public void OnPointerUp(PointerEventData e)
{
IsMouseDown = false;
}
void Update()
{
if (!IsMouseDown) return;
var m = Input.mousePosition;
var dx = LastMousePos.x - m.x;
var dy = LastMousePos.y - m.y;
var r = Screen.currentResolution;
var s = Speed / new Vector2(r.width, r.height).magnitude;
if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt)) s *= AltMultiplier;
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) s *= CtrlMultiplier;
var axis = new Vector3(-dy, dx, 0) * s;
axis = Camera.TransformDirection(axis);
transform.Rotate(axis, Space.World);
LastMousePos = m;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment