- Home /
Detect click on two objects that are on top of each other
In my 2D mobile game I have multiple "shelves" which are stacked vertically. They can be scrolled through by pressing on the screen and dragging your finger up/down. This is done through a parent object which contains all of the shelves as children and has its own box collider which covers the area of all of the shelves.
Here is the code for the parent object's click detection:
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
startPosY = mousePos.y - transform.localPosition.y;
fingerDown = true;
}
}
However, when the player taps and holds down on each individual shelf I have a UI menu which opens for managing the contents of the shelf.
Here is the code for the click detection on each shelf:
public void OnMouseDrag()
{
if (!locked)
{
upgradeMenuTimer += Time.deltaTime;
if (upgradeMenuTimer >= 1.5f)
{
OpenUpgradeMenu();
}
}
}
public void OnMouseUp()
{
if (!locked)
{
upgradeMenuTimer = 0f;
}
}
The problem is that if you press down on a shelf and try to scroll, it wont work because it is detecting the click through the child instead of the parent. It will only let me scroll if I click on the empty space in between each shelf. Ideally, the click would only be detected on the child if the player didn't move their finger while holding down on the shelf. If the player did move their finger the screen would scroll and cancel the opening of the menu. I know how to implement the logic for this system, I just need a way of detecting a click on both objects at once even though the colliders overlap. I have tried using a rigidbody on the parent but that results in the opposite problem, where clicking on the child only allows for scrolling and wont open the menu if i hold down on it.
Answer by xill · Aug 21, 2019 at 02:18 PM
Not really understand but what about Raycast.All if your colliders are overlapping, which goes trough objects and returns all?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
urgent, pls help. Selection through keyinput in Canvas 2 Answers
How to have two of the same UI Text? 1 Answer