- Home /
"Collision" between UI images
Hi. Sorry for my bad English. I'll get to the point:
I'm making a puzzle and I decided to do it completely using GUI elements; This is because most of the elements are static (except for the puzzle pieces) and it is not necessary to use physics.
The board consists, among other things, of sockets where the pieces will fit. I want that when a piece passes over a socket (over effect) it changes color. I had intended to use the IPointerEnterHandler interface, but the underlying event would only occur when the mouse pointer enters the socket and by the time this happens, the image of the piece would have entered this space long before. I want that effect to happen immediately after the image that represents the piece invades the space of the socket, not waiting for the pointer to do so. How could I get it? Thanks in advance.
Answer by RShields · Aug 15, 2018 at 01:04 AM
There are a few ways to do this, and here's one:
Add a BoxCollider2D (or similar) to all the pieces and sockets, and check "Is Trigger" on all. Then add a RigidBody2D [with Body Type: Kinematic] to each piece. On each socket, add a script like
private void OnTriggerEnter2D(Collider2D other)
{
PieceScript piece = other.GetComponent<PieceScript>();
if (piece != null)
piece.TouchingSocket(); // Or whatever function you want
}
(It actually doesn't matter where the script is [as long as you change it to fit] or where the RigidBody2D is, so long as there's only one script per piece-socket pair and at least one RigidBody2D per piece-socket pair.)
@RShields Thanks for answering.
Your solution was the first thing that came to $$anonymous$$d and that is what I would have done if I was using sprites ins$$anonymous$$d of UI images. I understand that it is not advisable to use RigidBody2D with elements of the interface.
Some of the other ways involve just doing the math yourself. If you're using circular objects, you can check distance from the picked up piece to every socket to see if they're close enough. If rectangular, check x and y distance. Really, I think you should be fine using colliders. If you're that concerned, it may be worthwhile to consider using sprites ins$$anonymous$$d of UI elements since UI elements aren't really designed to do collision.
Although I favor the use of sprites, if I follow the business logic of the application I intend to develop, "the mere use of UI elements is more convenient". Actually I can think of other ways to solve my problem as you say, but I did not want to use "rudimentary" solutions and I wanted to know through the forum if there were better alternatives. Thank you anyway.
Your answer
![](https://koobas.hobune.stream/wayback/20220612172827im_/https://answers.unity.com/themes/thub/images/avi.jpg)