OOP & Controller System
swarm controller
using System.Collections; using System.Collections.Generic; using UnityEngine; public class swarm_controller : MonoBehaviour { GameObject[] allBoids; public GameObject boid_prefab; public Transform target_trans_obj; public static float centerforce_factor = 1.5f; [Range(0f,15f)] public float centerforce_factor_ui = 1f; public static float separation_factor = .5f; [Range(0f,15f)] public float separation_factor_ui = 1f; // Start is called before the first frame update void Start() { initBoids(); } void initBoids(){ allBoids = new GameObject[159]; for(int i=0;i<150;i++){ GameObject ngo = Instantiate(boid_prefab); ngo.transform.position = Random.onUnitSphere; aBOID scrpt = ngo.GetComponent<aBOID>(); scrpt.target_trans = target_trans_obj; allBoids[i] = ngo; } } // Update is called once per frame void Update() { separation_factor = separation_factor_ui; centerforce_factor = centerforce_factor_ui; updateBoids(); } void updateBoids(){ for(int i=0;i<150;i++){ GameObject cgo = allBoids[i]; aBOID scrpt = cgo.GetComponent<aBOID>(); scrpt.updateMe(allBoids); //ngo.transform.position = Random.onUnitSphere; } } }
aBOID.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class aBOID : MonoBehaviour { Rigidbody rb; public Transform target_trans; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody>(); } // Update is called once per frame void Update() { } public void updateMe(GameObject[] allBs){ Vector3 centerforce = this.transform.position - target_trans.position; centerforce = centerforce.normalized*-swarm_controller.centerforce_factor; Debug.DrawLine(this.transform.position, this.transform.position + centerforce ,Color.blue,.01f); rb.AddForce(centerforce); for(int i=0; i< allBs.Length;i++){ if(allBs[i] == null){ return; } float disti = Vector3.Distance( this.transform.position, allBs[i].transform.position ); if(disti < .07f){ // Debug.Log(disti); // Debug.Log(i); //separation_force = this.transform.position;// - allBs[i].transform.position; Debug.DrawLine(this.transform.position,allBs[i].transform.position,Color.red,.01f); Vector3 separation_force = this.transform.position - allBs[i].transform.position; separation_force = separation_force.normalized * swarm_controller.separation_factor; rb.AddForce(separation_force); } } // Debug.Log("sepa" + separation_force); // // rb.AddForce(separation_force); } }