How to prevent object from entering other colliders
I have a script that allows my player to pick up objects, if it meets a certain criteria:
public void Pickup(GameObject item) {
items = item.GetComponent<Renderer> ();
theitem = item;
ObjectSize = items.bounds.size.magnitude;
carried = true;
}
// Update is called once per frame
void Update () {
if (carried) {
newitempos = gameObject.transform.position + Camera.main.transform.forward * range;
theitem.transform.position = newitempos;
if (Input.GetKeyUp(KeyCode.Mouse1)) {
carried = false;
theitem.GetComponent<Rigidbody> ().velocity = Vector3.zero;
}
}
}
However, since the object's motion is locked when it is being carried, it ends up going through other object's colliders, that are too heavy to move, or aren't allowed to move at all. I need a way to prevent this without causing too much work on the system.
Answer by kkiniaes · Dec 16, 2016 at 05:37 AM
This answer is based on the fact that your game sounds like a FPS; one thing that many games do is render objects that are being held by the main player on a separate camera that renders on top of everything else. This ensures that you can always see the item, and that it never accidentally culls with the environment.
This is somewhat effective, however, it doesn't eli$$anonymous$$ate the player's ability to move that object through the collider. I am still able to pick up objects, and move them outside of walls- meaning the player completely loses the object. It is also difficult to perceive the depth at which your item is at, to be able to accurately place it somewhere.
That's a good point, in that case you could have a script attached to the object that has an OnCollisionEnter implementation that can send a message back to the player indicating that it has entered a world collider.
You could also try to take advantage of the fact that when you child an object to a parent rigidbody, it's collision box is added to the bodys' collision system. In other words if the child has a collision box and the parent has a rigidbody, it will treat the childs collider as part of the total collider.
I've thought of the OnCollisionEnter idea, but having every gameobject in my scene that's 'movable' execute a script that's constantly checking for collisions seems like an unnecessary hassle and a lot of work for the system. However, I did attempt your second suggestion, and while it didn't fix the problem, it did fix another problem I was having- Thank you.