Is It Possible to Detect a Collision Within a Canvas?
Asked Answered
C

2

0

Hello all, for my game

I have a Canvas where the user can scroll through to select an item (using Scroll Rect). I have a collider in the center of the screen. The purpose of this collider is to detect which item is in the center of the screen (yes, the other images in the Scroll Rect has 2D colliders on them).

The goal is to display the name of the item that is in the center of the screen by detecting a collision with the collider (that is a trigger) in the middle of the screen, and the collider on the items that are being scrolled through. Here’s a snippet of my code:

public void OnTriggerEnter2D (Collider2D other)
{
    Debug.Log ("New item in center of screen");
    Text _text = GameObject.Find("Name").GetComponent<Text> ();
    _text.text = other.gameObject.name;
}

As the code states, when an image that has a 2D collider on it enters the collider in the middle of the screen, the name of the item should be displayed. This is not happening.

Any help!?

Cahoon answered 12/12, 2023 at 9:45 Comment(0)
C
0

Solved! For whatever reason, the detecting collider needed a Rigidbody2d component.

Works great now!

Cahoon answered 6/6, 2023 at 2:24 Comment(0)
G
0

The problem is that the collider exists in the world space and the canvas in the screen space. You can try convert the screen space into world space and transform the position.

But in such case which if I understood correctly you would like to make a “mini-game” on the screen that has no worry to cause collisions in the actual game.

It would be more reasonable to create 16:9 plane outside the game field where 3D or 2D objects with colliders and rigidbodies move and then mimic % positions of the plane to correlate Canvas space with Canvas UI elements.

Or just make another camera to point to that plane and layer it with your main camera.

Grecism answered 12/12, 2023 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.