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.