Last active
April 15, 2017 18:27
-
-
Save kaiware007/888d4071293dfde3af05b176ee5fb28d to your computer and use it in GitHub Desktop.
トラックボールっぽい回転(慣性付き)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class RotateTest : MonoBehaviour { | |
public Vector3 axis = Vector3.up; | |
public float rotSpeed = 0; | |
public float power = 0.1f; | |
public float friction = 0.98f; | |
public float stickPower = 100; | |
Vector3 prevPos; | |
Vector3 rotVec = Vector3.zero; // 回転ベクトル | |
Vector3 rotKeyVec = Vector3.zero; | |
float startTime; | |
// Update is called once per frame | |
void Update () { | |
// マウスフリックで操作 | |
if (Input.GetMouseButtonDown(0)) | |
{ | |
prevPos = Input.mousePosition; | |
startTime = Time.realtimeSinceStartup; | |
} | |
if (Input.GetMouseButtonUp(0)) | |
{ | |
Vector3 pos = Input.mousePosition; | |
Vector3 diff = pos - prevPos; | |
AddRotateVector(diff / (Time.realtimeSinceStartup - startTime)); | |
} | |
// 十字キーで操作 | |
rotKeyVec.x = Input.GetAxis("Horizontal"); | |
rotKeyVec.y = Input.GetAxis("Vertical"); | |
rotKeyVec = rotKeyVec.normalized * stickPower; | |
AddRotateVector(rotKeyVec); | |
// 摩擦 | |
rotVec *= friction; | |
rotSpeed = rotVec.magnitude; | |
transform.rotation = Quaternion.AngleAxis(rotSpeed * Time.deltaTime, axis) * transform.rotation; | |
} | |
/// <summary> | |
/// 回転ベクトル加算 | |
/// </summary> | |
/// <param name="vec"></param> | |
private void AddRotateVector(Vector3 vec) | |
{ | |
Vector3 diff2 = transform.position - Camera.main.transform.position; | |
diff2.Normalize(); | |
float p = vec.magnitude * power; // 回転速度計算 | |
vec.Normalize(); | |
rotVec += vec * p; // 足す | |
rotSpeed = rotVec.magnitude; // 新しい回転速度計算 | |
axis = Vector3.Cross(rotVec.normalized, diff2); // 新しい回転軸計算 | |
} | |
private void OnDrawGizmos() | |
{ | |
Vector3 pos = transform.position; | |
Gizmos.color = Color.red; | |
Gizmos.DrawLine(pos, pos + axis * 10f); | |
Gizmos.color = Color.cyan; | |
Gizmos.DrawLine(pos, pos + rotVec * 10f); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment