- Home /
Overlapping BoxCollider2D (as triggers) not working correctly OnMouseDown
I've made a simple 2D top-down farming game (like Farmville) and I've made a couple of GameObjects with prefabBrush which are plots for plants and the way it works is that Plot spawns a child GameObject which is a Plant.
Both parent (plot) and child (plant) have their own BoxCollision2D with IsTrigger on true, and the problem is that either first or the second collision works when I click on it (i.e. raises the OnMouseDown event in specific script), where I would like so that both would work at the same time, because I can water the plot (parent) AND use scythe to destroy growing weed (child) on such plot for example. Because they are in the same locations, their colliders usually overlap almost completely.
I've read a lot about solving such issue and people recommend using RayTracing for mouse capture in such cases, yet none of them show how to implement it properly step by step, so it would imitate OnMouseDown as close as possible, like should I trace it in some static GameHandler script? Because tracing it in every single script is not only ugly, but also seems very unefficient. How do I raise some kind of event from GameHandler script to clicked objects' scripts then?
At least I would prefer for child to take the priority, and other solution that I've found was to change the position of Z to be higher than parent, but it doesn't seem to work at all.
The only other thing that I've been thinking about was to use Composite Colliders and completely rearrange how the current plot/plant structure works, but I guess it would still behave inconsistently with adjacent plots and plants.
Any ideas?
Answer by xxmariofer · Nov 18, 2020 at 06:31 PM
Hello, For 2d objects dont use the Z, use the order in layer property a raycast example would be:
void YourMethod()
{
RaycastHit[] hits;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
hits = Physics.RaycastAll(ray);
foreach (RaycastHit hit in hits)
{
Debug.Log(hit.gameObject.name);
}
}
if you are afraid about its performance limit the ray lenght and play with the collision matrix to avoid unnecesary ray collisions
Your answer
Follow this Question
Related Questions
Trigger Triggers Without Collision 1 Answer
2D Isometric (2018.3b) - Collider 0 Answers
Unity2D: How to get an object to move along another objects shape? 2 Answers
How to make my object bounce off the screen bounds? 1 Answer
Can I create boundaries around my level without using box colliders? 3 Answers