Drag and Drop Objects in Game Problem

Hello, I am following this tutorial, and it works perfectly! However, I am able to drag objects through walls and colliders. Is there some kind of extra line of code someone can give me to add on to this script so that the player CAN’T drag the object through walls? Any help is GREATLY appreciated.

using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DragAndDrop : MonoBehaviour

{    
    private Vector3 mOffset;
       
    private float mZCoord;
    
    void OnMouseDown()

    {

        mZCoord = Camera.main.WorldToScreenPoint(

        gameObject.transform.position).z;

        // Store offset = gameobject world pos - mouse world pos

        mOffset = gameObject.transform.position - GetMouseAsWorldPoint();

    }


    private Vector3 GetMouseAsWorldPoint()

    {
           // Pixel coordinates of mouse (x,y)

        Vector3 mousePoint = Input.mousePosition;       

        // z coordinate of game object on screen

        mousePoint.z = mZCoord;    

        // Convert it to world points

        return Camera.main.ScreenToWorldPoint(mousePoint);

    }

    void OnMouseDrag()

    {

        transform.position = GetMouseAsWorldPoint() + mOffset;

    }

}

Because your script is just setting the position of the game object, no movement using physics occurs, so unity doesn’t check if the object hit anything along the way, only before and after the movement. One thing you could try is limiting how far the object can be dragged in one frame to reduce the chance of it completely skipping a wall. Here’s a very basic (untested) example you could try:

void OnMouseDrag() {
        Vector3 targetPosition = GetMouseAsWorldPoint() + mOffset;
        Vector3 toTargetPosition = targetPosition - transform.position;
        toTargetPosition = Vector3.ClampMagnitude(toTargetPosition, 0.1f * Time.deltaTime);
        targetPosition += toTargetPosition;
    }

Here “Vector3.ClampMagnitude” is used to limit the distance moved to 0.1 meters per frame. You will need to try tweak this number to get the desired max drag speed. Make sure your gameobject has a rigidbody or it wont collide at all!

@MUG806 , First of all, let me thank you for your very detailed answer! With the description of what your few lines do, it seems like it would work. However, after inserting these few lines, and then testing, it prevented me from even just picking up the cube. I even messed around with the 0.1f value and nothing changed. Feel free to use the main script I listed to continue testing your few lines, I might just have to just find another tutorial online. Thank you again.