Last active
February 26, 2018 00:37
-
-
Save unity3dcollege/f63f4bfc31a68c0772b29dbd2eeb6c66 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 UnityEngine; | |
public class GroundPlacementController : MonoBehaviour | |
{ | |
[SerializeField] | |
private GameObject placeableObjectPrefab; | |
[SerializeField] | |
private KeyCode newObjectHotkey = KeyCode.A; | |
private GameObject currentPlaceableObject; | |
private float mouseWheelRotation; | |
private void Update() | |
{ | |
HandleNewObjectHotkey(); | |
if (currentPlaceableObject != null) | |
{ | |
MoveCurrentObjectToMouse(); | |
RotateFromMouseWheel(); | |
ReleaseIfClicked(); | |
} | |
} | |
private void HandleNewObjectHotkey() | |
{ | |
if (Input.GetKeyDown(newObjectHotkey)) | |
{ | |
if (currentPlaceableObject != null) | |
{ | |
Destroy(currentPlaceableObject); | |
} | |
else | |
{ | |
currentPlaceableObject = Instantiate(placeableObjectPrefab); | |
} | |
} | |
} | |
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