Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created May 8, 2018 23:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unity3dcollege/6b94c626cbcec474f175a80a600e27cc to your computer and use it in GitHub Desktop.
Save unity3dcollege/6b94c626cbcec474f175a80a600e27cc to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
public class GroundPlacementController : MonoBehaviour
{
[SerializeField]
private GameObject[] placeableObjectPrefabs;
private GameObject currentPlaceableObject;
private float mouseWheelRotation;
private int currentPrefabIndex = -1;
private void Update()
{
HandleNewObjectHotkey();
if (currentPlaceableObject != null)
{
MoveCurrentObjectToMouse();
RotateFromMouseWheel();
ReleaseIfClicked();
}
}
private void HandleNewObjectHotkey()
{
for (int i = 0; i < placeableObjectPrefabs.Length; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha0 + 1 + i))
{
if (PressedKeyOfCurrentPrefab(i))
{
Destroy(currentPlaceableObject);
currentPrefabIndex = -1;
}
else
{
if (currentPlaceableObject != null)
{
Destroy(currentPlaceableObject);
}
currentPlaceableObject = Instantiate(placeableObjectPrefabs[i]);
currentPrefabIndex = i;
}
break;
}
}
}
private bool PressedKeyOfCurrentPrefab(int i)
{
return currentPlaceableObject != null && currentPrefabIndex == i;
}
private void MoveCurrentObjectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
currentPlaceableObject.transform.position = hitInfo.point;
currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}
}
private void RotateFromMouseWheel()
{
Debug.Log(Input.mouseScrollDelta);
mouseWheelRotation += Input.mouseScrollDelta.y;
currentPlaceableObject.transform.Rotate(Vector3.up, mouseWheelRotation * 10f);
}
private void ReleaseIfClicked()
{
if (Input.GetMouseButtonDown(0))
{
currentPlaceableObject = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment