user1295050
user1295050

Reputation: 145

unity 2D touch event blocked by something

I have my project setup like this:

Main Camera

Canvas

Blocking Mask: Nothing

2 Objects setup:

  1. GameObject

    • Sprite Renderer

    • Rigidbody 2D

    • Circle Collider 2D

    • (my GO script)

  2. UI

    • Image

    • Button

    • (my UI script)

In both my GO and UI script, I add OnPointerEnter event. and both work fine on their own. I can receive OnPointerEnter event.

But when I use a joint to drag a GO object and move to top of the UI object. My UI object OnPointerEnter blocked by the GO. I cannot receive the UI OnPointerEnter event.

I search on web and everybody ask for blocking raycast on GO to UI. But I need the reverse, I want both GO and UI receive OnPointerEnter event no matter if they overlap or not. Any hints?

P.S. something like this in 2D version, GameObject block UI Object. But I still want to receive UI Object OnPointerEnter.

enter image description here

Upvotes: 1

Views: 2117

Answers (1)

user1295050
user1295050

Reputation: 145

Finally get what I want. Now I have 2 solutions:

  1. using OnTriggerEnter2D
  2. turn off Physics2DRaycaster LayerMask GO when dragging GO

1. using OnTriggerEnter2D

  1. When drag GO. Shoot event to UI and tell which GO is dragging.
  2. Add rigibody2D(isKinematic and Freeze xyz) and 2Dcollider(is trigger) as component in UI object.
  3. OnTriggerEnter2D receive my GO collider and check if it is the dragging GO.(doing this because I excatlly want the UI get my only dragging GO).

2. turn off Physics2DRaycaster LayerMask GO when dragging GO

  1. use this code: using UnityEngine.EventSystems; public void turnOffLayerMask(string layerMaskName) { Physics2DRaycaster p2drc = Camera.main.GetComponent(); LayerMask layerMask = p2drc.eventMask; LayerMask disableLayerMask = 1 << LayerMask.NameToLayer(layerMaskName); p2drc.eventMask = layerMask & ~disableLayerMask; }
    public void turnOnLayerMask(string layerMaskName) { Physics2DRaycaster p2drc = Camera.main.GetComponent(); LayerMask layerMask = p2drc.eventMask; LayerMask enableLayerMask = 1 << LayerMask.NameToLayer(layerMaskName); p2drc.eventMask = layerMask | enableLayerMask; }

  2. turn off GO layerMask when dragging GO. Turn On back when drag end. The raycast can go through GO to UI and receive OnPointerXXX events.

I think the EventSystem auto. choose EITHER Physical raycast or Graphic raycast to detect GO/UI objects. So you can only receive either one set of event(Non-UI/ UI). Is it correct? It seems that I search on web and many people using OnMouseXXX (or other method) instead of Event system(i.e. OnPointerXXX). So they can "touch through" GO to UI.

Upvotes: 2

Related Questions