JohnnyTurbo

Unity Flow Field: UnitController.cs

Aug 14th, 2020 (edited)
890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class UnitController : MonoBehaviour
  6. {
  7.     public GridController gridController;
  8.     public GameObject unitPrefab;
  9.     public int numUnitsPerSpawn;
  10.     public float moveSpeed;
  11.  
  12.     private List<GameObject> unitsInGame;
  13.  
  14.     private void Awake()
  15.     {
  16.         unitsInGame = new List<GameObject>();
  17.     }
  18.  
  19.     void Update()
  20.     {
  21.         if (Input.GetKeyDown(KeyCode.Alpha1))
  22.         {
  23.             SpawnUnits();
  24.         }
  25.  
  26.         if (Input.GetKeyDown(KeyCode.Alpha2))
  27.         {
  28.             DestroyUnits();
  29.         }
  30.     }
  31.  
  32.     private void FixedUpdate()
  33.     {
  34.         if (gridController.curFlowField == null) { return; }
  35.         foreach (GameObject unit in unitsInGame)
  36.         {
  37.             Cell cellBelow = gridController.curFlowField.GetCellFromWorldPos(unit.transform.position);
  38.             Vector3 moveDirection = new Vector3(cellBelow.bestDirection.Vector.x, 0, cellBelow.bestDirection.Vector.y);
  39.             Rigidbody unitRB = unit.GetComponent<Rigidbody>();
  40.             unitRB.velocity = moveDirection * moveSpeed;
  41.         }
  42.     }
  43.  
  44.     private void SpawnUnits()
  45.     {
  46.         Vector2Int gridSize = gridController.gridSize;
  47.         float nodeRadius = gridController.cellRadius;
  48.         Vector2 maxSpawnPos = new Vector2(gridSize.x * nodeRadius * 2 + nodeRadius, gridSize.y * nodeRadius * 2 + nodeRadius);
  49.         int colMask = LayerMask.GetMask("Impassible", "Units");
  50.         Vector3 newPos;
  51.         for (int i = 0; i < numUnitsPerSpawn; i++)
  52.         {
  53.             GameObject newUnit = Instantiate(unitPrefab);
  54.             newUnit.transform.parent = transform;
  55.             unitsInGame.Add(newUnit);
  56.             do
  57.             {
  58.                 newPos = new Vector3(Random.Range(0, maxSpawnPos.x), 0, Random.Range(0, maxSpawnPos.y));
  59.                 newUnit.transform.position = newPos;
  60.             }
  61.             while (Physics.OverlapSphere(newPos, 0.25f, colMask).Length > 0);
  62.         }
  63.     }
  64.  
  65.     private void DestroyUnits()
  66.     {
  67.         foreach (GameObject go in unitsInGame)
  68.         {
  69.             Destroy(go);
  70.         }
  71.         unitsInGame.Clear();
  72.     }
  73. }
Add Comment
Please, Sign In to add comment