Unity/おすすめアセット/破壊オブジェクト
提供: 初心者エンジニアの簡易メモ
破壊アセット
WebGLで使える無料破壊アセット https://github.com/simplestargame/SimpleVoronoiFragmenter
使い方
- 適当にシーンを作る
- 3D/Cubeを新規で作る
- CubeのAddComponentからVoronoiFragmenterを追加
- VoronoiFragmenterのFragmentPrefabに、SimplestarGame/VoronoiFragmenter/Prefab/Fragment.prefabをドラッグして追加する
- MainCameraのAddComponentからSampleShooterを追加
- SampleShooterのMainCameraにMainCameraオブジェクトをドラッグ
- 動作させて、Cubeをクリックすうると破壊される
オブジェクトがピンクになる場合
Unity 2021.3.21f1以降か確認
オブジェクトが接触した箇所で破壊させる
VoronoiFragmenter.csを、以下のように一部修正して、FragmentPointメソッドで、Vector3を指定できるようにする。
修正前
namespace SimplestarGame
{
public class VoronoiFragmenter : MonoBehaviour
{
internal void Fragment(RaycastHit hit)
{
修正後
namespace SimplestarGame
{
public class VoronoiFragmenter : MonoBehaviour
{
internal void Fragment(RaycastHit hit)
{
FragmentPoint(hit.point);
}
internal void FragmentPoint(Vector3 hitPoint)
{
- ターゲットに接触するオブジェクト(Sphere)に、以下SphereColliderを追加する。
- ターゲット(Cube)のBoxColliderのIsTriggerにチェックを追加
using UnityEngine;
using SimplestarGame;
public class SphereCollider : MonoBehaviour
{
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.name == "Cube")
{
if (collider.gameObject.TryGetComponent(out VoronoiFragmenter voronoiFragment))
{
voronoiFragment.FragmentPoint(collider.gameObject.transform.position);
}
}
}
}
破壊オブジェクト同士が接触するように
- BoxColliderのIsTriggerをオフに
- SphereColliderを以下のように
これで破壊されたオブジェクトが、破壊予定のオブジェクトの上で止まるようになる
using System.Collections;
using UnityEngine;
using SimplestarGame;
using System.Text.RegularExpressions;
public class SphereCollider : MonoBehaviour
{
float scale = 0.6f;
float explosionRadius = 1f;
float explosionForce = 300f;
// 反発
IEnumerator CoExplodeObjects(Vector3 hitPoint, float scale)
{
yield return new WaitForFixedUpdate();
Collider[] colliders = Physics.OverlapSphere(hitPoint, this.explosionRadius);
foreach (var item in colliders)
{
if (item.TryGetComponent(out Rigidbody rigidbody))
{
rigidbody.isKinematic = false;
rigidbody.AddExplosionForce(this.explosionForce * scale, hitPoint + hitPoint * 0.1f, this.explosionRadius * scale);
}
}
}
// 重なり始めたとき
void OnCollisionEnter(Collision collision)
{
Match match = Regex.Match(collision.gameObject.name, "^Cube");
if (match.Success)
{
if (collision.gameObject.TryGetComponent(out VoronoiFragmenter voronoiFragment))
{
voronoiFragment.FragmentPoint(collision.gameObject.transform.position);
}
StartCoroutine(this.CoExplodeObjects(collision.gameObject.transform.position, scale));
}
}
}
