facebook twitter hatena line email

Unity/おすすめアセット/破壊オブジェクト

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

破壊アセット

WebGLで使える無料破壊アセット https://github.com/simplestargame/SimpleVoronoiFragmenter

使い方

  1. 適当にシーンを作る
  2. 3D/Cubeを新規で作る
  3. CubeのAddComponentからVoronoiFragmenterを追加
  4. VoronoiFragmenterのFragmentPrefabに、SimplestarGame/VoronoiFragmenter/Prefab/Fragment.prefabをドラッグして追加する
  5. MainCameraのAddComponentからSampleShooterを追加
  6. SampleShooterのMainCameraにMainCameraオブジェクトをドラッグ
  7. 動作させて、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)
        {
  1. ターゲットに接触するオブジェクト(Sphere)に、以下SphereColliderを追加する。
  2. ターゲット(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);
            }
        }
    }
}

破壊オブジェクト同士が接触するように

  1. BoxColliderのIsTriggerをオフに
  2. 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));
        }
    }
}