今回はUnityの2Dゲームで画像をマスキングして、表示したり隠したりしてみます。
はじめに
Unityのバージョンは2021.3.14f1です。
SpriteMaskを利用して画像を表示したり隠したりしてみます。
実装開始
まずはスプライト(画像)を2枚用意して並べ、隠したり表示したりします。
オブジェクト追加
「2DObject」→「Sprites」→「Square」を2つ追加します。それぞれの名前を「BlackBox」と「Internal」にします。

BlackBoxは色を黒にしてスケールを大きくします。

Internalは色を緑にしてスケールを小さくします。

「2DObject」→「SpriteMask」を追加します。

BlackBoxはMaskInteractionを「Visible OutSide Mask」に、Internalは「Visible Inside Mask」に変更します。

下記スクリプトを作成してSpriteMaskにアタッチします。
using UnityEngine; public class MaskPosition : MonoBehaviour { [SerializeField] private Camera _cam; void Update() { transform.position = (Vector2)_cam.ScreenToWorldPoint(Input.mousePosition); } }
実行してマウスを動かすと下記のような感じに。

通常は黒い箱(Balckbox)が表示され、中の画像(Internal)が隠されていますが、SpriteMaskを動かして黒箱の上にかぶせると黒い部分が消えて下の緑色が表示されます。
暗闇を歩くのような感じに
次に、SpriteMaskをinternalの配下に移動し、BlackBoxを画面全体を覆うようにします。下記のような感じですね。

SpriteMaskのスクリプトを外し、InternalにRigidbody2Dを追加、Gravityを0にして、Movementスクリプトをアタッチします。
Movementスクリプトは下記のように変更します。キー操作で動くようにしています。
using UnityEngine; public class Movement : MonoBehaviour { private float speed = 5.0f; private Rigidbody2D _rb; private Vector2 movement; private void Awake() { _rb = GetComponent<Rigidbody2D>(); } private void Update() { movement.x = Input.GetAxisRaw("Horizontal"); movement.y = Input.GetAxisRaw("Vertical"); _rb.velocity = movement * speed; } }
実行してキー操作すると、暗闇を動くような感じになります。
