Which gameObject is touched when touch at overlap gameObjects?
Hi, I am using Unity2D to write a card game, and lots of cards overlap with each others.
I sort the cards by order in layer, but when I touch on the top card, it is not the top card being touched, but some overlapped card pops out.
Any advice?
Answer by Oukalakakou · Mar 17, 2016 at 04:44 AM
If your cards are sorted by order in layer and are colliders you could do the following.
Get all your cards with the physics 2D cast you need for example OverlapPointAll. then sort your colliders and return the one that order in layer is the maximum.
Collider2D GetFrontCollider(Collider2D[] colliders){
int max = int.MinValue;
Collider2D collider = null;
for (int i=0; i<colliders.Length; i++) {
SpriteRenderer spr = colliders[i].GetComponent<SpriteRenderer>();
if(spr != null){
if (spr.sortingOrder > max) {
max = spr.sortingOrder;
collider = colliders [i];
}
}
}
return collider;
}
This should return the collider of a collider array which order in layer of the SpriteRenderer component is the maximum.
There must be a more elegant solution but this one should work though.
Your answer
Follow this Question
Related Questions
Cannot call trigger-event when dragging object via touch 1 Answer
Error CS1026: Unexpected symbol ;, expecting ) 0 Answers
UI Image not firing function constantly when held down. 1 Answer
Conditionals using TouchPhase.Ended 0 Answers
Simple cell-based game goes bonkers when clicked on the edge of the cell 0 Answers