2018年11月25日 星期日

龍捲風 物理

Tornado_Main Script (C#):

using UnityEngine;
using System.Collections;

public class Tornado_Main : MonoBehaviour {

    [Tooltip("This controls the radius of your tornados pull range")]
    public float radius = 65.28f;
    public float maxRadiusToPullIn = 10;
    [Tooltip("NEGATIVE NUMBERS ONLY. This pulls objects into the tornado")]
    public float PullingInPower = -70;
    public float MaxPullingIn = 20;

    Collider[] colliders;

    void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, radius);
    }
    
    void Update()
    {
        colliders = Physics.OverlapSphere(transform.position, radius);
        foreach (Collider c in colliders)
        {
            if (c.GetComponent<rigidbody>() == null)
            {
                continue;
            }
            Ray ray = new Ray(transform.position, c.transform.position - transform.position);
            RaycastHit hit;
            Physics.Raycast(ray, out hit);
            if (hit.collider.name != c.gameObject.name || hit.distance &lt; MaxPullingIn)
            {
                continue;
            }
            else
            {
                Rigidbody rigidbody = c.GetComponent<rigidbody>();
                rigidbody.AddExplosionForce(PullingInPower, transform.position, radius);
            }
        }
    }
}

Outer_Tornado Script(c#):

using UnityEngine;
using System.Collections;

public class Outer_Tornado : MonoBehaviour
{

    public float radius = 19.48f;
    public float outsideSpeed = 0.7f;
    public float maxPullInLength = 24.96f;
    public float power = 1;


    Collider[] colliders;

    void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, radius);
    }

    void Update ()
    {
        transform.RotateAround(transform.parent.transform.position, Vector3.up, outsideSpeed);
        colliders = Physics.OverlapSphere(transform.position, radius);
        foreach (Collider c in colliders)
        {
            if (c.GetComponent<rigidbody>() == null)
            {
                continue;
            }
            Rigidbody rigidbody = c.GetComponent<rigidbody>();
            Ray ray = new Ray(transform.position, c.transform.position - transform.position);
            RaycastHit hit;
            Physics.Raycast(ray, out hit);
            if (hit.distance &gt; maxPullInLength)
            {
                continue;
            }
            if (c.transform.position.z &gt; 8.5)
            {
                Vector3 Force = new Vector3(transform.position.x - c.transform.position.x, rigidbody.velocity.y / 2, transform.position.z - c.transform.position.z) * power;
                rigidbody.AddForceAtPosition(Force, transform.position);
            }
            rigidbody.AddForceAtPosition((transform.position - c.transform.position) * power, transform.position);
        }
    }
}

--------------
結果圖: