前回、Unityで「バナナをクリックしたらカウントする」を作成しました。今回は、アニメーションの追加などを行っていきます。
はじめに
前回作成したバナナクリックゲームは下記です。
今回は続きとして、バナナ(オブジェクト)のクリック範囲の修正とクリック時のアニメーション動作を追加していきます。
実装開始
クリック判定する範囲の修正、クリック時に画像を動かすアニメーションを作成していきます。
クリック判定の範囲を調整
現在はバナナ以外の場所(透過部分)でクリックしても反応するので、バナナの部分(実際の画像の範囲)だけで反応するようにしていきます。

「alphaHitTestMinimumThreshold」を利用して画像の透明部分(透過部分)では、クリックを判定しないようにしていきます。
スクリプトの変更
Bananaスクリプトを下記に変更します。
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Banana : MonoBehaviour, IPointerClickHandler { [SerializeField] private Text CountTxt; private int count; private Image image; private void Awake() { image = GetComponent<Image>(); image.alphaHitTestMinimumThreshold = 0.01f; } public void OnPointerClick(PointerEventData eventData) { count++; CountTxt.text = count.ToString(); } }
画像の設定で「Advanced」の「Read/Write」にチェックを入れます。

実行すると画像の透過部分でクリックしても反応しなくなります。実際の画像部分でのみ反応します。
アニメーションの追加
次に画像をクリックしたのを分かりやすくするため、アニメーションを追加して画像を動かしていきます。
画面上の「Window」→「Animation」→「Animation」を追加します。

「Create」をクリックして、Animationフォルダを作成して「bananaClick」という名前で保存します。

「Animation」には画像のScaleを指定していきます。ここは好きな間隔でOKです。

次に「Window」→「Animation」→「Animator」を選択します。

クリック時にアニメーションを動かすので、初期はidol状態にしておきます。Parametersで「OnClick」をトリガーとして追加します。

idol状態からクリック状態への移行設定は下記のような感じにします。

後はスクリプトにクリックしたときにトリガーをセットします。
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Banana : MonoBehaviour, IPointerClickHandler { [SerializeField] private Text CountTxt; private int count; private Image image; private Animator animator; private void Awake() { image = GetComponent<Image>(); image.alphaHitTestMinimumThreshold = 0.01f; animator = GetComponent<Animator>(); } public void OnPointerClick(PointerEventData eventData) { count++; CountTxt.text = count.ToString(); animator.SetTrigger("OnClick"); } }
実行すると下記のような感じに。クリックしたときにバナナのスケールが少し小さくなりクリックしているのがわかりやすくなります。

Animationはスケールを少し変更しているだけなので、DOTweenやコルーチン(IEnumerator)で作成する方が簡単かも。