Skip to content

Instantly share code, notes, and snippets.

@gamebox777
Created June 26, 2020 15:30
Show Gist options
  • Select an option

  • Save gamebox777/1339409db1ec3eef12e6b73953342978 to your computer and use it in GitHub Desktop.

Select an option

Save gamebox777/1339409db1ec3eef12e6b73953342978 to your computer and use it in GitHub Desktop.
クォータニオン超入門:軸に沿って回転させる
using UnityEngine;
using TMPro;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Quaternion01
{
public class Quaternion01 : MonoBehaviour
{
/// <summary> 回転させるモデル </summary>
public GameObject mModel;
/// <summary> 回転スピード </summary>
public float mRotSpeed = 1f;
/// <summary> テキスト </summary>
public TMP_Text mTextRot;
/// <summary> 回転させる軸 </summary>
private enum AxisType
{
None,
X,
Y,
Z
}
[SerializeField] AxisType mAxisType = AxisType.None;
/// <summary> 回転させる軸のベクトルデータ </summary>
private new readonly Vector3[] mRotVector = new[]
{
Vector3.zero,
Vector3.right, //X軸回転
Vector3.up, //Y軸回転
Vector3.forward, //Z軸回転
};
// Update is called once per frame
void Update()
{
//元の角度
var rot = mModel.transform.rotation;
//選択中の軸を元に回転させる回転量
var add = Quaternion.AngleAxis( mRotSpeed, mRotVector[(int)mAxisType] );
//角度を合成
mModel.transform.rotation = rot * add;
//Rotation表示
mTextRot.text = "Rotation(euler) " + rot.eulerAngles.ToString();
}
#if UNITY_EDITOR
//------------------------------------------------------------------------------------------
// エディタ拡張コード
//------------------------------------------------------------------------------------------
/// <summary>
/// Inspector拡張
/// </summary>
[CustomEditor(typeof(Quaternion01))]
public class Quaternion01Editor : Editor //!< Editorを継承するよ!
{
public override void OnInspectorGUI()
{
// target は処理コードのインスタンス。処理コードの型でキャストして使用
Quaternion01 quaternion01 = target as Quaternion01;
//元のInspector部分を表示
base.OnInspectorGUI ();
//ボタンを表示
if (GUILayout.Button("回転リセット"))
{
if (quaternion01 != null) {quaternion01.mModel.transform.rotation = Quaternion.identity;}
}
}
}
#endif //UNITY_EDITOR
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment