今回はUnity2Dゲームで「ブロックが壊れる(崩れる)エフェクト」を実装していきます。
アニメーションを利用する方法もありますが、今回はParticleSystemを利用してみます。
はじめに
「Unity 2021.3.3f1」ヴァージョンで作成しています。
まずは下記を参考に地面とプレイヤーを作成。
スクリプトを下記に変更してプレイヤーを動くようにします。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { [SerializeField] private float _PlayerSpeed; [SerializeField] private float _jumpPower; [SerializeField] private LayerMask _groundLayer; private Rigidbody2D _rb; void Start() { _rb = GetComponent<Rigidbody2D>(); } void Update() { float InputX = Input.GetAxisRaw("Horizontal"); if (Input.GetKey(KeyCode.Space) && isGrounded()) { _rb.velocity = new Vector2(_rb.velocity.x, _jumpPower); } _rb.velocity = new Vector2(InputX * _PlayerSpeed, _rb.velocity.y); } private bool isGrounded() { RaycastHit2D raycastHit = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, _groundLayer); return raycastHit.collider != null; } }
実装開始
まずはブロックを作成。2DObject→Sprites→Squareを追加。色は茶色にしておきます。


名前をBoxに変更して、ボックスコライダー2Dとスクリプトをアタッチ。

まずはスクリプトを下記に変更。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BreakBox : MonoBehaviour { private void OnTriggerEnter2D(Collider2D col) { Destroy(gameObject); } }
実行すると、下記の様にぶつかるとブロックが消えます。

この消える時に、ブロックを破壊したようなエフェクトを追加してみます。
Particle System
Boxの配下にEffects→Particle Systemを追加。

上向きにエフェクトを出すので、RotationのXを-90にします。

Projectフォルダ内にMaterialを新規で作成。

ShaderをParticlesにして、ブロックと同じ色に変更します。

Particle SystemのRendrerのMaterialを作成したマテリアルに変更。

下記の様にブロックが上に広がるようになります。

ParticleSystemの中身を変更。Duration、StartLifetime、StartSize、GravityModifierなどを変更して壊れて広がる感じにします。

スクリプトを下記に変更。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BreakBox : MonoBehaviour { [SerializeField] ParticleSystem _particle; private SpriteRenderer _rend; private void Awake() { _rend = GetComponent<SpriteRenderer>(); } private void OnTriggerEnter2D(Collider2D col) { StartCoroutine(BreakBox()); } private IEnumerator BreakBox() { _rend.enabled = false; _particle.Play(); yield return new WaitForSeconds(_particle.main.startLifetime.constantMax); Destroy(gameObject); } }
下記の様な感じになります。

この方法が最適かどうかは少し疑問ですが、こんな方法もあるって感じですね。Particle Systemは結構いろんなことに使えそうな感じですな。