Ui Collision Detection
Hello.
I would like to show within a canvas element some pictures, which can be moved by drag n` drop. Here, a collision detection to take place, which should prevent the images are placed over each other. I've already tried with Rigidbody2D and BoxCollider2D but unfortunately without success. I hope that who can help. My code currently looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragAndRotateHandler : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
private bool drag;
public void OnDrag( PointerEventData eventData )
{
if (drag)
{
transform.position = eventData.position;
}
}
public void OnPointerDown( PointerEventData eventData )
{
drag = true;
}
public void OnPointerUp( PointerEventData eventData )
{
drag = false;
}
private void OnTriggerEnter( Collider other )
{
Debug.Log("collission enter");
}
private void OnTriggerEnter2D( Collider2D collision )
{
Debug.Log("collission enter 2D");
}
private void OnTriggerStay( Collider other )
{
Debug.Log("collission stay");
}
private void OnTriggerStay2D( Collider2D collision )
{
Debug.Log("collission stay 2D");
}
private void OnTriggerExit( Collider other )
{
Debug.Log("collission exit");
}
private void OnTriggerExit2D( Collider2D collision )
{
Debug.Log("collission exit 2D");
}
}
Thanks for your help
I don't think Physics 2D work inside canvas. $$anonymous$$aybe if you change canvas to World space or make sprite ins$$anonymous$$d of UI texture might work
He does not display sprites in the canvas. As a space element, unfortunately, I am not there because I need the ui in front of the camera. I am moving in the background about a Large 3D map. Is there another way to detect the collision of 2 images in the canvas? Thank you for your answer.
I do this once. But it was much simpler, i just box in the image. Like get 4 corners positioned. If anyone of them get out of border. Call update position that force them go back.
Not optimal but work for simple drag image game
$$anonymous$$any Thanks. I'll do it for now until maybe there is a better possibility in Unity. Thank you