コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】NGUIのスプライトにマウスポインタが重なった時の演出を実装する

using UnityEngine;

public class ButtonMotion : MonoBehaviour
{
    public float Duration = 0.2f;
    public float MinScale = 1;
    public float MaxScale = 1.5f; 
    public float Elastic = 0.4f;
        
    private float mTime;
    private bool mIsHover;

    private void Awake()
    {
        mTime = Duration;
    }

    private void Update()
    {
        mTime += Time.deltaTime;
            
        var t = Mathf.Clamp01( mTime / Duration );

        var v0 = Mathf.Sin( Mathf.PI * 0.5f * t );
        var vx = v0 + Mathf.Sin( Mathf.PI * 2f * v0 ) * Elastic;
        var vy = v0 - Mathf.Sin( Mathf.PI * 2f * v0 ) * Elastic;

        if ( !mIsHover )
        {
            vx = 1 - vx;
            vy = 1 - vy;
        }

        var localScale = transform.localScale;
        localScale.x = Mathf.Lerp( MinScale, MaxScale, vx );
        localScale.y = Mathf.Lerp( MinScale, MaxScale, vy );
        transform.localScale = localScale;
    }

    private void OnHover( bool isOver )
    {
        mIsHover = isOver;
        mTime = 0;
    }
}
  1. 上記のスクリプトを ButtonMover.cs という名前で Unity プロジェクトに追加する
  2. UISprite と BoxCollider がアタッチされたオブジェクトに ButtonMover.cs をアタッチする

f:id:baba_s:20140927150804p:plain