AsteroidGame/Assets/Handlers/BuildingHandler.cs

127 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using AsteroidGame.Entities.Structures.Scripts;
using UnityEngine;
using UnityEngine.InputSystem;
namespace AsteroidGame.Handlers
{
public class BuildingHandler : HandlerBase
{
[Header("Connections")] [SerializeField]
private new Camera camera;
[Header("State")] [SerializeField] private bool isBuilding;
[SerializeField] private int buildingSelector;
[Header("Prefabs")] [SerializeField] private List<StructureBase> buildings = new();
#region Private
[SerializeField] private List<StructureBase> activeBuildings;
private Vector3 _tempVec;
private Plane _buildPlane;
private StructureBase _tempSb;
private StructureBase _ghostStructure;
#endregion
protected override void OnEnable()
{
base.OnEnable();
_buildPlane = new Plane(Vector3.up, Vector3.zero);
activeBuildings.Clear();
camera = Camera.main;
}
private void Update()
{
if (isBuilding)
{
_ghostStructure.transform.position = GetPlanePoint();
}
}
protected override void OnLeftClick(InputAction.CallbackContext context)
{
PlaceStructure();
}
protected override void OnRightClick(InputAction.CallbackContext context)
{
if (!isBuilding) return;
DestroyGhostStructure();
isBuilding = false;
}
protected override void OnBuild(InputAction.CallbackContext context)
{
EnterBuildMode();
}
public void PlaceStructure()
{
AbortPlaceStructure();
}
public void AbortPlaceStructure()
{
if (!isBuilding) return;
if (_ghostStructure.BuildPlacementBlocked) return;
DestroyGhostStructure();
SpawnStructure();
isBuilding = false;
}
public void EnterBuildMode()
{
isBuilding = true;
SpawnGhostStructure();
}
private void SpawnGhostStructure()
{
_ghostStructure = Instantiate(buildings[buildingSelector], GetPlanePoint(), Quaternion.identity, transform);
_ghostStructure.name = "GhostStructure";
var rb = _ghostStructure.gameObject.AddComponent<Rigidbody>();
rb.useGravity = false;
// foreach (var renderer in _ghostStructure.GetComponents<MeshRenderer>())
// {
// var color = renderer.material.color;
// var tempcolor = color;
// tempcolor.a = 0.1f;
// color = tempcolor;
// }
_ghostStructure.GetComponent<StructureBase>().enabled = false;
}
private void DestroyGhostStructure()
{
Destroy(_ghostStructure.gameObject);
}
private void SpawnStructure()
{
_tempSb = Instantiate(buildings[buildingSelector], GetPlanePoint(), Quaternion.identity, transform);
activeBuildings.Add(_tempSb);
}
private Vector3 GetPlanePoint()
{
Ray ray = camera.ScreenPointToRay(Mouse.current.position.ReadValue());
if (_buildPlane.Raycast(ray, out float distance))
{
return ray.GetPoint(distance);
}
else
{
print("BuildPlaneNotHit");
return Vector3.zero;
}
}
}
}