IMHOTEP Framework
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Pages
CanvasRaycaster.cs
1 using UnityEngine;
2 using UnityEngine.EventSystems;
3 using UnityEngine.UI;
4 using System.Collections;
5 using System.Collections.Generic;
6 
10 public class CanvasRaycaster : BaseRaycaster {
11 
12  Canvas m_Canvas = null;
13  private Canvas canvas
14  {
15  get {
16  if (m_Canvas != null)
17  return m_Canvas;
18 
19  m_Canvas = GetComponent<Canvas> ();
20  return m_Canvas;
21  }
22  }
23 
24  public override Camera eventCamera {
25  get {
26  return InputDeviceManager.instance.currentInputDevice.getEventCamera();
27  }
28  }
29 
30  public override void Raycast( PointerEventData data, List<RaycastResult> resultAppendList )
31  {
32  if (canvas == null)
33  return;
34 
35 
36  Camera cam = InputDeviceManager.instance.currentInputDevice.getEventCamera();
37  Vector3 worldPos = canvas.transform.TransformPoint (new Vector3(data.position.x, data.position.y, 0 ));
38 
39  Vector3 screenPosition = cam.WorldToScreenPoint (worldPos);
40 
41  Rect fullCanvas = GetComponent<RectTransform> ().rect;
42 
43  if (data.position.x > fullCanvas.size.x || data.position.y > fullCanvas.size.y)
44  return;
45 
46  List<Graphic> sortedGraphics = new List<Graphic> ();
47 
48  var foundGraphics = GraphicRegistry.GetGraphicsForCanvas (canvas);
49  for (int i = 0; i < foundGraphics.Count; ++i) {
50  Graphic graphic = foundGraphics [i];
51 
52  if (graphic.depth == -1 || !graphic.raycastTarget)
53  continue;
54 
55  Vector2 localPos = positionFromCanvasSpaceToGraphicSpace (graphic, data.position);
56  if (!graphic.rectTransform.rect.Contains (localPos))
57  continue;
58 
59  sortedGraphics.Add (graphic);
60  }
61 
62  sortedGraphics.Sort ((g1, g2) => g2.depth.CompareTo (g1.depth));
63 
64 
65  for (int i = 0; i < sortedGraphics.Count; ++i) {
66  Graphic graphic = sortedGraphics [i];
67  var castResult = new RaycastResult {
68  gameObject = graphic.gameObject,
69  module = this,
70  distance = i,
71  screenPosition = new Vector2( screenPosition.x, screenPosition.y ),//positionFromCanvasSpaceToGraphicSpace (graphic, data.position),
72  index = resultAppendList.Count,
73  depth = graphic.depth,
74  sortingLayer = canvas.sortingLayerID,
75  sortingOrder = canvas.sortingOrder
76  };
77  resultAppendList.Add( castResult );
78  }
79  }
80 
81  public Vector2 positionFromCanvasSpaceToGraphicSpace( Graphic graphic, Vector2 pos )
82  {
83  // First, convert the position to world space:
84  Vector3 worldPos = GetComponent<RectTransform> ().TransformPoint (pos.x, pos.y, 0);
85 
86  // Then inverse-transform it back to local space:
87  Vector3 result = graphic.rectTransform.InverseTransformPoint( worldPos );
88  return new Vector2 (result.x, result.y);
89  }
90 }