How to stop mouse drag of a rigidbody when it collides with wall (also rigidbody)

Hi All, i have a problem: i have a main cube in which i have a camera and other small cubes a sort of 3d desktop).
The cubes are obviously the icons.
I have a function tha drag them but they exit fron the walls around.
All the itema are non gravity and non kinematic rigidbody and the code i use for dragging is;

using UnityEngine;
using System.Collections;

public class MoveIcons : MonoBehaviour
{

		Vector3 initPos;

		// Use this for initialization
		void Start ()
		{

		}
	
		// Update is called once per frame
		void Update ()
		{
			initPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
		}
	
		void OnMouseDrag ()
		{
				float distance_to_screen = Camera.main.WorldToScreenPoint (gameObject.transform.position).z;
				transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
		
		}

		void OnCollisionEnter (Collision col)
		{
			if(col.gameObject.name == "Right")
			{
				Debug.Log("Right");
				transform.position = initPos;
			}

		}

}

How can i stop or reset the position of the icon while dragging if it collides with the walls?

Try making it like this:

using UnityEngine;

using System.Collections;

 

public class MoveIcons : MonoBehaviour

{
        Vector3 initPos;
        private bool colided = false;

        void Update ()

        {
            initPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        }
    
        void OnMouseDrag ()
        {
                if(colided == true) return;
                float distance_to_screen = Camera.main.WorldToScreenPoint (gameObject.transform.position).z;
                transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
        }

        void OnCollisionEnter (Collision col)
        {
            if(col.gameObject.name == "Right")
            {
                Debug.Log("Right");
                transform.position = initPos;
                colided = true;
            }
        }

 

}
1 Like

Many thanks, but this don’t work: i have all the icons rotatig along their Y axis, so when a corner collides the icon blocks but the rotation continues…
Where i have to add animation.Stop()?
I’ve tried in mouse drag but that blocks all the dragging…
I’ve tried in update with Input.GetMouseButton(0)…
Nothing…

1 Like