|
|
|
|
|
|
using UnityEditor; |
|
|
|
using UnityEngine; |
|
|
|
using UnityEngine; |
|
|
|
|
|
|
|
[ExecuteInEditMode] |
|
|
|
[AddComponentMenu("UOP1/Tools/Click to Place")] |
|
|
|
|
|
|
[SerializeField] float _verticalOffset = 0.1f; |
|
|
|
[SerializeField] private float _verticalOffset = 0.1f; |
|
|
|
private Vector3 _spawnPosition; |
|
|
|
private bool _displaySpawnPosition = false; |
|
|
|
private Vector3 _targetPosition; |
|
|
|
private delegate void ButtonAction(); |
|
|
|
private ButtonAction myButtonAction; |
|
|
|
public bool IsTargeting { get; private set; } |
|
|
|
if (_displaySpawnPosition) |
|
|
|
if (IsTargeting) |
|
|
|
Gizmos.DrawCube(_spawnPosition, Vector3.one * 0.3f); |
|
|
|
Gizmos.DrawCube(_targetPosition, Vector3.one * 0.3f); |
|
|
|
void OnMouseClick(SceneView scene) |
|
|
|
public void BeginTargeting() |
|
|
|
Event currentGUIEvent = Event.current; |
|
|
|
|
|
|
|
Vector3 mousePos = currentGUIEvent.mousePosition; |
|
|
|
float pixelsPerPoint = EditorGUIUtility.pixelsPerPoint; |
|
|
|
mousePos.y = scene.camera.pixelHeight - mousePos.y * pixelsPerPoint; |
|
|
|
mousePos.x *= pixelsPerPoint; |
|
|
|
|
|
|
|
Ray ray = scene.camera.ScreenPointToRay(mousePos); |
|
|
|
|
|
|
|
if (Physics.Raycast(ray, out RaycastHit hit)) |
|
|
|
{ |
|
|
|
_spawnPosition = hit.point + Vector3.up * _verticalOffset; |
|
|
|
|
|
|
|
if (currentGUIEvent.type == EventType.MouseMove) |
|
|
|
{ |
|
|
|
HandleUtility.Repaint(); |
|
|
|
} |
|
|
|
if (currentGUIEvent.type == EventType.MouseDown |
|
|
|
&& currentGUIEvent.button == 0) // Wait for Left mouse button down
|
|
|
|
{ |
|
|
|
myButtonAction(); |
|
|
|
SceneView.duringSceneGui -= OnMouseClick; |
|
|
|
_displaySpawnPosition = false; |
|
|
|
|
|
|
|
currentGUIEvent.Use(); // This consumes the event, so that other controls/buttons won't be able to use it
|
|
|
|
} |
|
|
|
} |
|
|
|
IsTargeting = true; |
|
|
|
_targetPosition = transform.position; |
|
|
|
public void SetSpawnLocationAtCursor() |
|
|
|
public void UpdateTargeting(Vector3 spawnPosition) |
|
|
|
Debug.Log("Use the LMB to position this object"); |
|
|
|
myButtonAction = SetTransform; |
|
|
|
_displaySpawnPosition = true; |
|
|
|
SceneView.duringSceneGui += OnMouseClick; |
|
|
|
_targetPosition = spawnPosition + Vector3.up * _verticalOffset; |
|
|
|
/// <summary>
|
|
|
|
/// The delegate called when the mouse is clicked in the viewport
|
|
|
|
/// </summary>
|
|
|
|
private void SetTransform() |
|
|
|
public void EndTargeting() |
|
|
|
transform.position = _spawnPosition; |
|
|
|
Debug.Log("Object moved to " + _spawnPosition); |
|
|
|
IsTargeting = false; |
|
|
|
transform.position = _targetPosition; |
|
|
|
} |
|
|
|
} |