-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMouseDrag.cs
72 lines (66 loc) · 2.28 KB
/
MouseDrag.cs
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
using UnityEngine;
using UnityEngine.EventSystems;
public class MouseDrag : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
private Vector2 lastMousePosition;
/// <summary>
/// This method will be called on the start of the mouse drag
/// </summary>
/// <param name="eventData">mouse pointer event data</param>
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("Begin Drag");
lastMousePosition = eventData.position;
}
/// <summary>
/// This method will be called during the mouse drag
/// </summary>
/// <param name="eventData">mouse pointer event data</param>
public void OnDrag(PointerEventData eventData)
{
Vector2 currentMousePosition = eventData.position;
Vector2 diff = currentMousePosition - lastMousePosition;
RectTransform rect = GetComponent<RectTransform>();
Vector3 newPosition = rect.position + new Vector3(diff.x, diff.y, transform.position.z);
Vector3 oldPos = rect.position;
rect.position = newPosition;
if (!IsRectTransformInsideSreen(rect))
{
rect.position = oldPos;
}
lastMousePosition = currentMousePosition;
}
/// <summary>
/// This method will be called at the end of mouse drag
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("End Drag");
}
/// <summary>
/// This methods will check is the rect transform is inside the screen or not
/// </summary>
/// <param name="rectTransform">Rect Trasform</param>
/// <returns></returns>
private bool IsRectTransformInsideSreen(RectTransform rectTransform)
{
bool isInside = false;
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
int visibleCorners = 0;
Rect rect = new Rect(0, 0, Screen.width, Screen.height);
foreach (Vector3 corner in corners)
{
if (rect.Contains(corner))
{
visibleCorners++;
}
}
if (visibleCorners == 4)
{
isInside = true;
}
return isInside;
}
}