Help with grabbing object code
Hey there! I am working on grabbing some objects. I am using this script and my problem is that when i grab something it can go through walls floor etc, as it doesn't have box collider. Any solution to that?
using UnityEngine;
using System.Collections;
public class Grab : MonoBehaviour {
GameObject grabbedObject;
float grabbedObjectSize;
GameObject GetMouseHoverObject(float range)
{
Vector3 position = gameObject.transform.position;
RaycastHit raycastHit;
Vector3 target = position + Camera.main.transform.forward * range;
if (Physics.Linecast(position, target, out raycastHit))
return raycastHit.collider.gameObject;
return null;
}
void TryGrabObject(GameObject grabObject)
{
if (grabObject == null || !CanGrab(grabObject))
return;
grabbedObject = grabObject;
grabbedObjectSize = grabObject.GetComponent<Renderer>().bounds.size.magnitude;
}
bool CanGrab(GameObject canidate)
{
return canidate.GetComponent<Rigidbody> () != null;
}
void DropObject()
{
if (grabbedObject == null)
return;
if (grabbedObject.GetComponent<Rigidbody> () != null)
grabbedObject.GetComponent<Rigidbody> ().velocity = Vector3.zero;
grabbedObject = null;
}
void Update () {
if (Input.GetMouseButtonDown(1))
{
if (grabbedObject == null)
TryGrabObject(GetMouseHoverObject(5));
else
DropObject();
}
if (grabbedObject != null)
{
Vector3 newPosition = gameObject.transform.position+Camera.main.transform.forward*grabbedObjectSize;
grabbedObject.transform.position = newPosition;
}
}
}
Answer by JedBeryll · Dec 04, 2015 at 10:32 PM
Add a box collider? No seriously, if you don't want it to collide with anything else you can set up collision layers. http://docs.unity3d.com/Manual/LayerBasedCollision.html
Other than that you can set the grabbing object as parent of the grabbedObject.
Your answer
Follow this Question
Related Questions
How To Make An Object Appear In Front Of Player Without Cloning? 1 Answer
Collision detection in 2017 3d 4.2f2 0 Answers
Find active Child gameobject out of multiple gameobjects 2 Answers
Need help with GameObject placement 2 Answers
How to Parent a Camera to the Head Bone with No Camera Shake? 0 Answers