ブログ

周囲の敵を吹き飛ばす(AddExplosionForce)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hado : MonoBehaviour
{
    [SerializeField]
    private GameObject hadoArea;
    private Vector3 scale;

    private float radius = 0;
    public float power;

    private void Start()
    {
        scale = hadoArea.transform.localScale;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            scale.x += 0.05f;
            scale.y += 0.05f;
            scale.z += 0.05f;
            hadoArea.transform.localScale = scale;

            radius += 0.05f;
        }

        if (Input.GetKeyUp(KeyCode.Space))
        {
            Vector3 explosionPos = transform.position;
            Collider[] enemies = Physics.OverlapSphere(explosionPos, radius);

            foreach (Collider hit in enemies)
            {
                Rigidbody rb = hit.GetComponent<Rigidbody>();

                if (rb != null)
                {
                    rb.AddExplosionForce(power, explosionPos, radius, 8f, ForceMode.Impulse);
                }
            }

            radius = 0.0f;
            scale.x = 0f;
            scale.y = 0f;
            scale.z = 0f;
            hadoArea.transform.localScale = scale;
        }
    }
}