0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity】AddExplosionForceサンプル

Posted at

#実装動画

AddExplosionForce (float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifier= 0.0f, ForceMode mode= ForceMode.Force));

とりあえず以下のパラメータで設定。

  • explosionForce = 100
  • explosionRadius = 20
  • upWardsModifier = 3.0f(球体的な爆発をシミュレートするため、見かけ上の位置を調整する。)
  • mode = Impulse

#実装
###cubeオブジェクト生成
爆発を受ける対象物をStart時に自動生成。
特殊なことはやらず、愚直にforで回して生成する。

CreateCube.cs
using UnityEngine;

public class CreateCube : MonoBehaviour
{
    public GameObject cube;
    public int interval = 2;

    private int startPosition = -30;
    private float startYPosition = 0.5f;
    private int finishPosition = 30;
    private float finishYPosition = 10.5f;

    void Start()
    {
        for (int z = startPosition; z <= finishPosition; z+=interval)
        {
            for (float y = startYPosition; y < finishYPosition; y+=interval)
            {
                for (int x = startPosition; x <= finishPosition; x += interval)
                {
                    Instantiate(cube, new Vector3(x, y, z), Quaternion.identity);
                }
            }
        }
    }
}

###AddExplosionForceの実装
こちらののっぴの備忘録さんの記事を参考に作成。

Blast.cs
using UnityEngine;

public class Blast : MonoBehaviour
{
    public float power = 100f;
    public float radius = 20.0f;
    public float upwardsModifier = 3.0f;

    Ray ray;
    RaycastHit hit;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //クリック点にRayを飛ばす
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 100f))
            {
                //クリックした所から半径20mの範囲のColliderを取得
                Collider[] collider = Physics.OverlapSphere(hit.point, radius);
                foreach (Collider cube in collider)
                {
                    //範囲内のオブジェクトのRigidbodyに爆破の力を作用させる
                    if (cube.GetComponent<Rigidbody>())
                    {
                        cube.GetComponent<Rigidbody>().
                            AddExplosionForce(power, hit.point, radius, upwardsModifier, ForceMode.Impulse);
                    }
                }
            }
        }
    }
}

#終わり

  • 爆発をシミュレートすることが出来た。ただ爆発してモノを壊すだけのゲームを作成したい。
  • 注意点として、被爆発対象の物体にはrigidbodyを付けないとシミュレートできない。
  • 数値を変えた検証動画も作成したいなぁと思ってます。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?