using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
private bool lockCam = false;
private void Update() {
HandleCameraMovement();
HandleCameraRotation();
if (UnitActionSystem.Instance.GetSelectedUnit() != null && Input.GetKeyDown(KeyCode.L)) {
lockCam = !lockCam;
}
if (lockCam) {
transform.position = UnitActionSystem.Instance.GetSelectedUnit().transform.position;
}
}
private void HandleCameraMovement() {
float moveSpeed = 10f;
Vector3 inputMoveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
transform.Translate(new Vector3(inputMoveDir.x, 0, inputMoveDir.z) * moveSpeed * Time.deltaTime, Space.Self);
}
private void HandleCameraRotation() {
float rotationSpeed = 100f;
Vector3 rotationVector = new Vector3(0, 0, 0);
if (Input.GetKey(KeyCode.Q)) {
rotationVector.y++;
}
else if (Input.GetKey(KeyCode.E)) {
rotationVector.y--;
}
transform.eulerAngles += rotationVector * rotationSpeed * Time.deltaTime;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitActionSystem : MonoBehaviour {
public static UnitActionSystem Instance { get; private set; }
public event EventHandler OnSelectedUnitChanged;
private GridSystem gridSystem;
[SerializeField] private Unit selectedUnit;
[SerializeField] private LayerMask unitLayerMask;
public List<Unit> availableUnits = new List<Unit>();
private int index;
private void Awake() {
Instance = this;
}
private void Update() {
for (int i = 0; i < availableUnits.Count; i++) {
availableUnits[i].gameObject.name = "Unit " + (i + 1);
}
if (Input.GetMouseButton(1)) {
SetSelectedUnit(null);
}
if (Input.GetMouseButton(0)) {
if (HandleUnitSelection()) return;
GridPosition gridPosition = LevelGrid.Instance.GetGridPosition(MouseWorld.GetMouseWorldPosition());
if (selectedUnit != null) {
selectedUnit.Move(LevelGrid.Instance.GetWorldPosition(gridPosition));
}
}
if (selectedUnit != null) {
UnitSelectionTraversal();
}
}
private void UnitSelectionTraversal() {
if (index == availableUnits.Count) {
index = 0;
}
if (Input.GetKeyDown(KeyCode.K)) {
index++;
}
else if (Input.GetKeyDown(KeyCode.J)) {
if (index == 0) {
index = availableUnits.Count;
}
index--;
}
if (index < availableUnits.Count) {
SetSelectedUnit(availableUnits[index]);
}
}
private bool HandleUnitSelection() {
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out var hit, float.MaxValue, unitLayerMask)) {
if(hit.transform.TryGetComponent<Unit>(out Unit unit)) {
SetSelectedUnit(unit);
index = availableUnits.IndexOf(unit);
return true;
}
}
return false;
}
private void SetSelectedUnit(Unit unit) {
selectedUnit = unit;
OnSelectedUnitChanged?.Invoke(this, EventArgs.Empty);
}
public Unit GetSelectedUnit() => selectedUnit;
}