Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Collision between UI-image and normal GameObject

Discussion in 'Scripting' started by smarart, Feb 16, 2023.

  1. smarart

    smarart

    Joined:
    Feb 16, 2023
    Posts:
    4
    1. I have a GameObject with a collider.
    2. I have an UI-image, which is draggable with:
    Code (CSharp):
    1.  public void OnDrag(PointerEventData eventData) {
    2.         rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
    3.  
    4.     }
    3. I have no idea how i can get info back when they collide? Is it even possible to make ui object and normal gameobjec to have a collision?

    The idea is to drag an UI object over normal sprite, and get the object name or reference back.

    Danke schön.


    And i noticed that UI and my camera are totally in a different world view, so i decided to make an gameobject wich follows the UI-element which is being dragged, so the following element could notice the collisions. It follows the ui-element but still wont recognize collisions.
    Code (CSharp):
    1.  
    2. void Update()
    3.     {
    4.         mvp = cam.ScreenToWorldPoint(rectTrans.position);
    5.         Vector3 vec = new Vector3(mvp.x, mvp.y, 0);
    6.         this.gameObject.GetComponent<Transform>().position = vec;
    7.     }
    8.  
    9.     void OnCollisionEnter(Collision col) {
    10.  
    11.         Debug.Log(col);
    12.     }
    13.  
    EDIT: Now it works, i forgot to add the Rigidbody.
    Anyways, is this a good way to make an "draggable" item, which gives you info about the colliding object. ie. Key -> door. or magnifying glass --> painting.
     
    Last edited: Feb 17, 2023
  2. FlashMuller

    FlashMuller

    Joined:
    Sep 25, 2013
    Posts:
    449
    They will not collide as in Physics Collision. You could use ScreenPointToRay --> Unity - Scripting API: Camera.ScreenPointToRay (unity3d.com) to achieve what you want. On Drag cast one (or more, e.g. for each corner of your UI Object) Rays into the world, check for their collision with your object and use that information.
    You should find plenty info on ScreenPointToRay in the forums.
     
    smarart likes this.