Files
TutorialRTS/Assets/Scripts/UnitCommander.cs

91 lines
3.1 KiB
C#
Raw Normal View History

2026-03-19 17:31:51 +00:00
using System.Diagnostics.Contracts;
using System.Xml.Serialization;
2026-03-19 11:57:23 +00:00
using UnityEngine;
public class UnitCommander : MonoBehaviour
{
2026-03-19 17:31:51 +00:00
public GameObject selectionMarkerPrefab;
public LayerMask layerMask;
//components
private UnitSelection unitSelection;
private Camera cam;
void Awake()
{
//get the components
unitSelection = GetComponent<UnitSelection>();
cam = Camera.main;
}
2026-03-19 11:57:23 +00:00
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
2026-03-19 17:31:51 +00:00
if(Input.GetMouseButtonDown(1) && unitSelection.HasUnitSelected())
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Unit[] selectedUnits = unitSelection.GetSelectedUnits();
if(Physics.Raycast(ray, out hit, 100, layerMask))
{
if(hit.collider.CompareTag("Ground"))
{
SelectionMarker marker = CreateSelectionMarker(hit.point, false);
UnitsMoveToPosition(hit.point, selectedUnits, marker);
}
else if(hit.collider.CompareTag("Resource"))
{
UnitsGatherResource(hit.collider.GetComponent<ResourceSource>(), selectedUnits);
CreateSelectionMarker(hit.point, true);
}
}
}
}
void UnitsMoveToPosition(Vector3 movePos, Unit[] units, SelectionMarker marker)
{
for(int x = 0; x < units.Length; x++)
{
// Only the first unit owns the marker so it isn't destroyed multiple times
units[x].MoveToPosition(movePos, x == 0 ? marker : null);
}
}
//creates a new selection marker at the position we right click
SelectionMarker CreateSelectionMarker(Vector3 pos, bool large)
{
GameObject marker = Instantiate(selectionMarkerPrefab, pos + new Vector3(0, 0.01f, 0), Quaternion.identity);
if(large)
marker.transform.localScale = Vector3.one * 3;
return marker.GetComponent<SelectionMarker>();
}
//called when we command units to move somewhere
void MoveUnitsToPosition(Vector3 movePos, Unit[] units)
{
Vector3[] destinations = UnitMover.GetUnitGroupDestination(movePos, units.Length, 2);
for(int x = 0; x < units.Length; x++)
{
units[x].MoveToPosition(destinations[x]);
}
}
//called when we command units to gather a resource
void UnitsGatherResource(ResourceSource resource, Unit[] units)
{
2026-03-19 22:32:52 +00:00
if(units.Length == 1)
{
units[0].GatherResource(resource, UnitMover.GetUnitDestinationAroundResource(resource.transform.position));
}
else
{
Vector3[] destinations = UnitMover.GetUnitGroupDestinationsAroundResource(resource.transform.position, units.Length);
for(int x = 0; x <units.Length; x++)
{
units[x].GatherResource(resource, destinations[x]);
}
}
2026-03-19 11:57:23 +00:00
}
}