-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventSystemDragExample.cs
More file actions
100 lines (83 loc) · 2.69 KB
/
EventSystemDragExample.cs
File metadata and controls
100 lines (83 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// Example implementing pointer click and drag (using event system events)
/// </summary>
[RequireComponent(typeof(Collider))]
public class EventSystemDragExample : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
private static readonly Color dragColor = Color.green;
[SerializeField]
new Camera camera;
[SerializeField]
Vector3 dragOffset;
[Header("Drag Plane"), SerializeField]
Vector3 dragPlaneNormal = Vector3.up;
[SerializeField]
float planeDistance = 0;
[SerializeField]
BoxCollider dragBounds;
private Plane plane;
private Color originalColour;
private Material material;
private void Start()
{
if(camera == null)
{
camera = Camera.main;
}
var renderer = GetComponent<Renderer>();
if(renderer != null)
{
material = renderer.material;
}
//Make plane with serialized settings
plane = new(dragPlaneNormal, planeDistance);
}
public void OnBeginDrag(PointerEventData eventData)
{
//Change colour of material if one exists
// This helps indicate that we began dragging
if(material != null)
{
originalColour = material.color;
material.color = dragColor;
}
}
public void OnEndDrag(PointerEventData eventData)
{
//Restore colour of renderer if one exists
if(material != null)
{
material.color = originalColour;
}
}
/// <summary>
/// Implements dragging this gameobject on an imaginary plane using event system pointer drag event
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
//Using pointer screen position from event data, make a ray
Ray ray = camera.ScreenPointToRay(eventData.position);
//Perform a raycast with our plane
//The distance from the ray origin to a plane intersection is returned
if(plane.Raycast(ray, out float distance))
{
//Use raycast hit distance to project forward and get the point in world space where our raycast actually hit the collider
Vector3 newWorldPosition = ray.GetPoint(distance) + dragOffset;
//Clamp position inside bounds (if assigned)
if(dragBounds != null)
{
newWorldPosition = dragBounds.ClosestPoint(newWorldPosition);
}
transform.position = newWorldPosition;
}
}
#if UNITY_EDITOR
private void Reset()
{
camera = FindFirstObjectByType<Camera>();
}
#endif
}