Choose Top from 2D Pile

I am using Unity 5 and making a 2D game in which many sprites will be stacked on top of each other and can then be moved by dragging. Sometimes when the users goes to drag from a pile, ones that aren’t on the top are dragged instead. Is there any way to make sure that the one that is dragged is the one on top? Thanks

Hi,

Apply your script on the container of your 2D pile and use transform.GetChild();. Index can ben known with transform.childCount !

  • If the top of your pile is the first child in the hierarchy, use transform.GetChild(0);
  • If the top is the last child, use transform.GetChild(transform.childCount - 1);

Use RayCast2DAll and sort the array of hits by distance.

using System.Linq;

RaycastHit2D[] hits = Physics2D.RaycastAll(ray.origin, ray.direction, Mathf.Infinity, layerMask, -Mathf.Infinity, Mathf.Infinity).OrderBy(h=>h.distance).ToArray();

Now you can loop through the array and the first element will always be the closest hit (meaning: the one on top).