Albertkaruna
Albertkaruna

Reputation: 85

How to ignore mouse click at background layers or objects?

I'm developing simple fix it kind of games. Here if i clicked at the object it will instantiate new layer in front of the background layer. But the problem is when i click on the top layer the click also affects the background layer. How to avoid it? I used layer based collision and collider on the top layer but no use.

Upvotes: 2

Views: 4753

Answers (3)

Albertkaruna
Albertkaruna

Reputation: 85

Before i get the answer i did this by using animation. If i'm interacting with the top layer then i removed the background layer from background after the top layer work is done then the i placed background layer. Is this good or bad?

Upvotes: 0

ゴスエン ヘンリ
ゴスエン ヘンリ

Reputation: 843

3D or 2D?

check this out: OnMouseDown on box collider 2D not firing

I would also check for specific tags and create different modes to check them, like.

int mode=0;

In 'mode 0' would check the collision for #basicLayers, in 'mode 1' would check for #topLayers

Like (using the above link answer +suggestion):

void check3DObjectClicked ()
{
    if (Input.GetMouseButtonDown (0)) {

        RaycastHit hitInfo = new RaycastHit ();
        if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo)) {
            Debug.Log ("Object Hit is " + hitInfo.collider.gameObject.name);

           switch(mode){
           case 0:
               if (hitInfo.collider.gameObject.CompareTag ("basicLayerObject1"){
                   mode=1;
                   //do stuff
               }
           break;

           case 1:
               if (hitInfo.collider.gameObject.CompareTag ("createdTopLayerObj1"){
                   mode=2;
                   //do stuff
               }else if (hitInfo.collider.gameObject.CompareTag ("quitTopLayer"){
                   mode=0;
                   //do stuff
               }
               //ignoring basicLayers tagged objects on background.
           break;
           }

       } 
   } 
}

hope this make sense somehow.

Upvotes: 2

Raimund Krämer
Raimund Krämer

Reputation: 1309

I recommend using a raycast. When you click, cast from the mouse cursor into the scene and check for the object's tag (or other attributes if you need to). This way, you do not have to use OnMouseOver() or OnMouseDown() on many different objects, and have the logic in a single place.

It is also more flexible, for example you can specify the range of the raycast as well as ignoring certain layers.

Upvotes: 2

Related Questions