nirasan's tech blog

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

NGUI の UITweener の Animation Curve に任意の曲線を設定する

はじめに

  • Unity + NGUI で TweenPosition や TweenAlpha などの UITweener を継承したコンポーネントで Animation Curve の曲線をプログラムから設定する方法についてメモ。

バージョン

  • Unity 4.6.1f1
  • NGUI 3.7.6

設定方法

  • Animation Curve の曲線は AnimationCurve クラスで設定する
  • コンストラクタは AnimationCurve(Keyframe[])
  • Keyframe は曲線上の任意の点で Keyframe(x, y) で x が時間軸、y が変化量になる。
    • Keyframe の x は、開始地点が 0 で、終了地点が 1 になる。duration が 3秒 なら「x:0 = 0秒」で「x:1 = 3秒」となる。
    • Keyframe の y は、開始地点が 0 で、終了地点が 1 になる。TweenAlpha で変化前が 1 で変化後の値が 0 なら「y:0 = 1」で「y:1 = 0」となる。

コード例

開始から半分の時間まで変化しない場合

GameObject go = GameObject.Find("Path/To/Any/GameObject");
UITweener tw = TweenAlpha.Begin(go, 1f, 0.5f);
tw.animationCurve = new AnimationCurve(
	new Keyframe(  0f, 0f),
	new Keyframe(0.5f, 0f),
	new Keyframe(  1f, 1f)
);

点滅する場合

GameObject go = GameObject.Find("Path/To/Any/GameObject");
UITweener tw = TweenAlpha.Begin(go, 1f, 0.5f);
tw.animationCurve = new AnimationCurve(
	new Keyframe(  0f, 0f),
	new Keyframe(0.2f, 1f)
	new Keyframe(0.4f, 0f),
	new Keyframe(0.6f, 1f)
	new Keyframe(0.8f, 0f),
	new Keyframe(  1f, 1f)
);

Keyframe に入る角度と出る角度の指定をする

  • Keyframe のコンストラクタで Keyframe(x, y, inTangent, outTangent) というパターンが有り inTangent と outTangent で曲線の入る角度と出る角度を指定できる。
  • inTangent, outTangent の単位は tangent なので、角度を指定したい場合は変換する必要がある。

角度からタンジェントへの変換

// 角度からタンジェントへ
float DegreesToTan (float degrees) {
	return Mathf.Tan(DegreesToRadians(degrees));
}
// 角度からラジアンへ
float DegreesToRadians (float degrees) {
	return degrees * Mathf.PI / 180f;
}

コード例

イーズアウト

GameObject go = GameObject.Find("Path/To/Any/GameObject");
UITweener tw = TweenAlpha.Begin(go, 1f, 0.5f);
tw.animationCurve = new AnimationCurve(
	new Keyframe(0f, 0f, 0f, DegreesToTan(70f)),
	new Keyframe(1f, 1f, DegreesToTan(10f), 0f)
};

イーズイン

GameObject go = GameObject.Find("Path/To/Any/GameObject");
UITweener tw = TweenAlpha.Begin(go, 1f, 0.5f);
tw.animationCurve = new AnimationCurve(
	new Keyframe(0f, 0f,                0f, 0f),
	new Keyframe(1f, 1f, DegreesToTan(70f), 0f)
};

波を描く

GameObject go = GameObject.Find("Path/To/Any/GameObject");
UITweener tw = TweenAlpha.Begin(go, 1f, 0.5f);
tw.animationCurve = new AnimationCurve(
	new Keyframe(   0f,   0f,                 0f,                 0f),
	new Keyframe(0.25f, 0.5f, DegreesToTan(-85f), DegreesToTan(-85f)),
	new Keyframe(0.5f,  0.5f, DegreesToTan(-85f), DegreesToTan(-85f)),
	new Keyframe(0.75f, 0.5f, DegreesToTan(-85f), DegreesToTan(-85f)),
	new Keyframe(   1f,   1f,                 0f,                 0f)
};