-
-
Save zackperdue/270e9574bed4a937bef791fb41512291 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class ConstructionController : MonoBehaviour | |
{ | |
private bool isBuilding = false; | |
private GameObject item; | |
[SerializeField] | |
private GameObject itemPrefab; | |
private LayerMask terrainLayermask; | |
[SerializeField] | |
private float maxDistance = 12f; | |
[SerializeField] | |
private GameObject placementIndicatorPrefab; | |
private GameObject placementIndicator; | |
private float smooth = 10f; | |
private void Awake() | |
{ | |
terrainLayermask = 1 << 17; | |
isBuilding = false; | |
} | |
// Update is called once per frame | |
void Update() | |
{ | |
// Enable building mode | |
if (Input.GetKeyDown(KeyCode.E)) | |
{ | |
isBuilding = !isBuilding; | |
if (isBuilding) | |
{ | |
placementIndicator = Instantiate(placementIndicatorPrefab, transform.position + Vector3.forward * maxDistance, transform.rotation); | |
} | |
} | |
// While building mode is enabled... | |
if (isBuilding) | |
{ | |
// Place item | |
if (Input.GetKeyDown(KeyCode.Alpha1)) | |
{ | |
item = Instantiate(itemPrefab, Camera.main.transform.position + transform.forward * maxDistance, transform.rotation); | |
} | |
if (item != null) { | |
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); | |
RaycastHit hit; | |
if (Physics.Raycast(ray, out hit, maxDistance, terrainLayermask)) | |
{ | |
Vector3 offset = item.transform.position - hit.point; | |
item.transform.position = Vector3.Lerp(item.transform.position, hit.point, Time.deltaTime * smooth); | |
} | |
} | |
} | |
// Cancel building mode | |
if (Input.GetKeyDown(KeyCode.Escape)) | |
{ | |
if (isBuilding) | |
{ | |
isBuilding = false; | |
Destroy(item); | |
Destroy(placementIndicator); | |
} | |
} | |
} | |
private void OnDrawGizmos() | |
{ | |
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); | |
RaycastHit hit; | |
if (Physics.Raycast(ray, out hit, Mathf.Infinity, terrainLayermask)) | |
{ | |
Gizmos.DrawWireSphere(hit.point, 1f); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment