Created
May 8, 2018 23:38
-
-
Save unity3dcollege/6b94c626cbcec474f175a80a600e27cc to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
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