I have a simple script that uses Raycasting to pick up objects with a specific script, but the objects can still move through walls. I was just wondering how I might prevent this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickupObject : MonoBehaviour {
GameObject mainCamera;
bool carrying;
GameObject carriedObject;
public float distance;
public float smooth;
// Start is called before the first frame update
void Start()
{
mainCamera = GameObject.FindWithTag("MainCamera");
}
// Update is called once per frame
void Update()
{
if (carrying)
{
carry(carriedObject);
checkDrop();
}
else
{
pickup();
}
}
void carry(GameObject o)
{
o.GetComponent<Rigidbody>().isKinematic = true;
o.transform.position = Vector3.Lerp (o.transform.position, mainCamera.transform.position + mainCamera.transform.forward * distance, Time.deltaTime * smooth);
carriedObject.gameObject.layer = 7;
}
void pickup()
{
if (Input.GetMouseButtonDown(0))
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x,y));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 5))
{
Pickup p = hit.collider.GetComponent<Pickup>();
if (p != null)
{
carrying = true;
carriedObject = p.gameObject;
}
}
}
}
void checkDrop() {
if (Input.GetMouseButtonUp(0)) {
dropObject();
}
if (carriedObject == null)
{
Debug.Log("gone");
}
void dropObject() {
carrying = false;
carriedObject.gameObject.GetComponent<Rigidbody>().isKinematic = false;
carriedObject = null;
}
}
}