Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Weird OnMouseX behaviour with Camera.eventMask and RigidBody2D

Discussion in 'Physics' started by sharkwithlasers, May 1, 2021.

  1. sharkwithlasers

    sharkwithlasers

    Joined:
    Dec 8, 2012
    Posts:
    23
    Hi there,

    I have a use-case where I have an object with a Collider2D and a Kinematic RigidBody2D in order to do Kinematic movement.

    However, I also want to be able to select/hover that object with a OnMouseDown/OnMouseEnter/etc, using a larger collider than I would use for the kinematic movement.

    My current attempt at a solution is to have Physics-related scripts/rigidbody2d/collider2d as the top level game object, and to have a child object, with a larger collider2D which will respond to OnMouseX events.

    upload_2021-4-30_21-1-33.png

    upload_2021-4-30_21-2-36.png upload_2021-4-30_21-2-50.png

    In order to ignore OnMouseX events on the parent, I'm putting it into its own `user_ignore_raycasts` layer (I need it as its own layer for the layer collision matrix). I'm also putting the child in its own `user_use_raycasts` layer.

    I'm passing that into a script that sets Camera's event mask:
    upload_2021-4-30_21-6-13.png

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3.  
    4. [RequireComponent(typeof(Camera))]
    5. public class CameraEventMasker : MonoBehaviour
    6. {
    7.     [SerializeField]
    8.     private LayerMask cameraEventMask;
    9.  
    10.     // Start is called before the first frame update
    11.     void Awake()
    12.     {
    13.         GetComponent<Camera>().eventMask = cameraEventMask;
    14.     }
    15. }
    ...

    What I notice is that OnMouseX events on the child will work IF the RigidBody2D on the parent is deleted...however, if the RigidBody2D is there, I won't receive any events. Anyone know why this is the case, and if there are other workarounds or solutions?
     

    Attached Files:

  2. rubcc95

    rubcc95

    Joined:
    Dec 27, 2019
    Posts:
    222
    Rigidbody eats all the mouse events at his children colliders, i.e. all colliders behave as one for event purposes, and they trigger the event from the parent gameObject where the rigidbody is hosted. Just attach your Mouse Downer to the same GameObject than the rigidbody, and it will still work with the nested collider.
     
    sharkwithlasers likes this.
  3. sharkwithlasers

    sharkwithlasers

    Joined:
    Dec 8, 2012
    Posts:
    23
    Ahh, that seems to work for me. Interesting that it will still trigger events on the parent even if the child collider is in a different layer than the parent gameobject.

    Thanks!