Collision detection while dragging object?

I have written a small script that allows the player to pick-up an object and move it around the scene using the crosshairs in the center of the screen. Although, while moving an object like this, there is no collision detection, how would I get an object to move, but not through other objects? The game is first person and Raycasting is done from the center of the screen.

using UnityEngine;
using System.Collections;

public class ObjectInteract : MonoBehaviour
{
	
	RaycastHit hit;
	private Transform cam;
	private float dist = 0;
	private int interactableLayer;
	private Transform target;
	
	// Use this for initialization
	void Start ()
	{
		cam = Camera.main.transform;
		interactableLayer = LayerMask.NameToLayer ("Interactable");
	}
	
	// Update is called once per frame
	void Update ()
	{
		if (Physics.Raycast (cam.position, cam.forward, out hit, 3)) {
			if (Input.GetButtonDown ("Select")) {
				dist = Vector3.Distance (hit.point, transform.position);
				target = hit.transform;
			}
		}
		
		Rigidbody rb = null;
		
		if (target != null)
			rb = target.GetComponent<Rigidbody> ();
		
		if (Input.GetButton ("Select")  rb  target.gameObject.layer == interactableLayer) {
			rb.isKinematic = true;
			target.transform.position = transform.position + (cam.forward.normalized * dist);
		}
		
		if (Input.GetButtonUp ("Select")  rb) {
			rb.isKinematic = false;
			target.transform.parent = null;
			target = null;
		}
	}
}

Any help in any form is greatly appreciated.

I finally understood the reason and sharing it… it might help the others…

2 Likes

Good job, two years out but late is better than never! Good video though, thanks!

1 Like

Necro-solution!

Here is a simple script that will accomplish what you want

using UnityEngine;

public class DragObject : MonoBehaviour {
    private Rigidbody rb;
    private bool isDragging = false;
    private Vector3 offset;
   
    void Start() {
        rb = GetComponent<Rigidbody>();
    }
   
    void OnMouseDown() {
        isDragging = true;
        offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
    }
   
    void OnMouseUp() {
        isDragging = false;
    }
   
    void FixedUpdate() {
        if (isDragging) {
            Vector3 newPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)) + offset;
            rb.MovePosition(newPosition);
        }
    }
}