- Home /
How can I prevent an invisible collider from intercepting an OnMouseDown() event?
In the game I'm building, I need the user to be able to click on the black sphere object shown here:
However, because in this game the objects are supposed to pile up on the platform underneath, I have put up some invisible kinematic rigidbody walls.
The problem is that the OnMouseDown() event is not being triggered in most cases because the invisible walls are in the way. I believe this is the case because there are some gaps in the walls and if I click in between the gaps, the event executes.
How can I get it so that the invisible walls are ignored for the purpose of triggering the black sphere's OnMouseDown() event, but still behave as a kinematic object that prevent the boxes and sphere from falling off the platform?
Fire a raycast that ignores the walls. then return the name of what it hit
I'm giving this as a comment since it is untested. Can you put your walls on the 'Ignore Raycast' layer? Another possibility is to build the walls out of plane mesh collider rather than box colliders. mesh colliders are one sided.
Answer by valim · Jan 04, 2014 at 12:37 PM
Use a raycast. Here's a bit of code that can help: You should put the sphere into a new layer and whatToCollideWith should be only that layer.
public float distanceLimit = 10000f;
public LayerMask whatToCollideWith;
void Update(){
if(Input.GetMouseButtonDown(0)){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, distanceLimit, whatToCollideWith)) {
// Clicked();
}
}
You should rename the OnMouseDown to Clicked, or any name.
I didn't tested myself.
Answer by XDeltas · Jan 04, 2014 at 08:31 AM
Use a raycast to test if your click would hit the ball and set the walls to Ignore raycast layer and you could try robertbu's suggestion to use a plane mesh collider. Then depending on what happens after the ball is clicked, you would either have the raycast change a value on the ball and use a script to check when the value changes, or have the balls identified by name and have the raycast output the name of the object hit. Hope this sums up the answer.