Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Last active September 25, 2020 01:09
Show Gist options
  • Save MikuroXina/f606b456cb7c61c7cad3d6047d100f81 to your computer and use it in GitHub Desktop.
Save MikuroXina/f606b456cb7c61c7cad3d6047d100f81 to your computer and use it in GitHub Desktop.
An example of exclusion control in Unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotator : MonoBehaviour {
// SerializeField 属性をつけると
// エディタのInspectorから値を操作できます
[SerializeField] float duration = 0.13f; // アニメーションする長さ
// 実行中の回転処理
IEnumerator rotateTask = null;
// ボタンに対応する回転軸を Dictionary コンテナを使って定義
Dictionary<string, Vector3> operationMap = new Dictionary<string, Vector3>() {
{ "Right", new Vector3(0, -1, 0) },
{ "Down", new Vector3(-1, 0, 0) },
{ "Up", new Vector3(1, 0, 0) },
{ "Left", new Vector3(0, 1, 0) }
};
void Update() {
// 回転中であれば
if (rotateTask != null) {
// キャンセル
return;
}
// operationMap から各対応付けを取り出し
foreach (var map in operationMap) {
// ボタン押下時に
if (Input.GetButtonDown(map.Key)) {
// その回転軸で回転する Coroutine を始める
rotateTask = RotateAnim(map.Value);
StartCoroutine(rotateTask);
}
}
}
IEnumerator RotateAnim(Vector3 axis) {
var start = Time.time;
var original = transform.rotation; // 回転前の姿勢を保持しておきます
// 回転後の姿勢 = 軸に沿って 90 度回す * 回転前の姿勢
var target = Quaternion.Euler(axis * 90) * original;
while (Time.time - start < duration) {
// 時間の進んだ割合(0 ~ 1) = (Time.time - start) / duration
var progress = (Time.time - start) / duration;
// Slerp(q0, q1, t) で 2 つの回転が球状に補間されます
transform.rotation = Quaternion.Slerp(original, target, progress);
yield return null; // 次のフレームへ
}
transform.rotation = target; // 回転後をセットして行き過ぎ防止
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment