読者です 読者をやめる 読者になる 読者になる

nirasan's tech blog

趣味や仕事の覚え書きです。Linux, Perl, PHP, Ruby, Javascript, Android, Cocos2d-x, Unity などに興味があります。

Unity で二つの値の間を行き来する値の取得方法2種類

Mathf.PingPong

  • t を基準にして 0 から length までの値を返す
返り値の例
Debug.Log (Mathf.PingPong(0f, 3f)); //=> 0
Debug.Log (Mathf.PingPong(0.5f, 3f)); //=> 0.5
Debug.Log (Mathf.PingPong(1f, 3f)); //=> 1
Debug.Log (Mathf.PingPong(2f, 3f)); //=> 2
Debug.Log (Mathf.PingPong(3f, 3f)); //=> 3
Debug.Log (Mathf.PingPong(3.5f, 3f)); //=> 2.5
Debug.Log (Mathf.PingPong(4f, 3f)); //=> 2
Debug.Log (Mathf.PingPong(5f, 3f)); //=> 1
Debug.Log (Mathf.PingPong(6f, 3f)); //=> 0
Update での使用例
  • 1秒間に0からlengthまで1往復する例
float sumTime = 0;
float duration = 1.0f;
float length = 3f;
void Update () {
    sumTime += Time.deltaTime;
    Debug.Log (Mathf.PingPong (sumTime * length / duration * 2, length));
}

Mathf.Sin

返り値の例
Debug.Log (Mathf.Sin (0f * Mathf.Deg2Rad)); //=> 0
Debug.Log (Mathf.Sin (10f * Mathf.Deg2Rad)); //=> 0.1736482
Debug.Log (Mathf.Sin (20f * Mathf.Deg2Rad)); //=> 0.3420201
Debug.Log (Mathf.Sin (30f * Mathf.Deg2Rad)); //=> 0.5
Debug.Log (Mathf.Sin (40f * Mathf.Deg2Rad)); //=> 0.6427876
Debug.Log (Mathf.Sin (50f * Mathf.Deg2Rad)); //=> 0.7660444
Debug.Log (Mathf.Sin (60f * Mathf.Deg2Rad)); //=> 0.8660254
Debug.Log (Mathf.Sin (70f * Mathf.Deg2Rad)); //=> 0.9396926
Debug.Log (Mathf.Sin (80f * Mathf.Deg2Rad)); //=> 0.9848077
Debug.Log (Mathf.Sin (90f * Mathf.Deg2Rad)); //=> 1
Debug.Log (Mathf.Sin (100f * Mathf.Deg2Rad)); //=> 0.9848077
Debug.Log (Mathf.Sin (110f * Mathf.Deg2Rad)); //=> 0.9396926
Debug.Log (Mathf.Sin (120f * Mathf.Deg2Rad)); //=> 0.8660254
Debug.Log (Mathf.Sin (130f * Mathf.Deg2Rad)); //=> 0.7660444
Debug.Log (Mathf.Sin (140f * Mathf.Deg2Rad)); //=> 0.6427876
Debug.Log (Mathf.Sin (150f * Mathf.Deg2Rad)); //=> 0.8660254
Debug.Log (Mathf.Sin (160f * Mathf.Deg2Rad)); //=> 0.3420202
Debug.Log (Mathf.Sin (170f * Mathf.Deg2Rad)); //=> 0.1736483
Debug.Log (Mathf.Sin (180.0f * Mathf.Deg2Rad)); //=> -8.742278E-08
Update での使用例
  • 1秒間に0から1まで1往復する例
float sumTime = 0;
void Update () {
    sumTime += Time.deltaTime;
    Debug.Log (Mathf.Sin (180 * sumTime * Mathf.Deg2Rad));
}