Problem is not reproducible or outdated
Issue with fbx box collider
Hi,
In my project I have to instantiate a fbx model and add a box collider on it, based on children's bounds (because the parent is an empty gameobject). I used the following code (picked up from other answers):
public class CreateBoxCollider : MonoBehaviour {
void Start () {
Quaternion currentRotation = this.transform.rotation;
this.transform.rotation = Quaternion.Euler (0f, 0f, 0f);
Bounds bounds = new Bounds (this.transform.position, Vector3.zero);
foreach (Renderer renderer in GetComponentsInChildren<Renderer>()) {
bounds.Encapsulate (renderer.bounds);
}
Vector3 localCenter = bounds.center - this.transform.position;
bounds.center = localCenter;
this.transform.rotation = currentRotation;
BoxCollider bc = this.GetComponent<BoxCollider> ();
bc.center = localCenter;
bc.size = bounds.size;
}
}
The problem is that the box collider created on the parent with this script is much bigger than the model. Here's the result :
The y size seems right, but is there a reason why x and z sizes aren't ?
Answer by TailKitty · Apr 06, 2017 at 09:24 AM
Is it really necessary to create box colliders dynamically?
Just make a prefab out of your FBX model and add appropriate box collider on every single bone in your model which you need directly in the editor.
After, just instantiate your ready to go prefab instead.
Note: use void OnTriggerEnter(Collider col) event to detect collision instead of OnCollisionEnter to avoid some strange mismatches with collisions. It gives me a lot of troubles then I was using OnCollisionEnter event instead...
Yes it's necessary to create box colliders dynamically because I'm not supposed to know the model that will be instantiated. The user can add any FBX model of his choice in Assets/Resources.
I already tried to add a box collider on every bones, and it worked, but I want to create a box collider that completely encompasses the model because I have to manipulate the model with Leap $$anonymous$$otion and it will be much simpler this way. Plus, the FBX $$anonymous$$odel may have hundreds of pieces so...
The Leap $$anonymous$$otion manipulation script only works with void OnTriggerEnter by the way.
Follow this Question
Related Questions
Dice going through walls using Raycast hit distance 0 Answers
Rotating Object When Clicked and Rotating Back When Clicked Again C# 1 Answer
Player passing through walls when in corners 0 Answers
Changing light color between players when they collide (BOLT) 0 Answers
How to find the distance between unknown object and player 1 Answer