- Home /
How do I fix 2d collisions when I parent one object to another?
Object A Object B
I have a script that sets A's transfrom.parent to B's transform when A collides with B. Up until this point object A has a 2d collider and a 2d rigidbody. Object B has a collider and is a child of an object with a kinematic 2d rigidbody. When the parenting occurs, I destroy the rigidbody on object A. Now other 2d colliders pass through object A's collider, even though its a normal collider at best, or a static collider at worst.
But if I go into the editor during play and move the object A manually after it has been parented, objects will start colliding with object A again.
I would like to have collisions work for object A without having to manually move it.
Here is the code:
tarGameObject.transform.parent = gameObject.transform;
tarGameObject.transform.localPosition = new Vector3();
tarGameObject.transform.localRotation = Quaternion.identity;
Destroy( tarGameObject.rigidbody2D );
Thanks for your time.
If I disable and enable the 2d collider on object A, collisions work again. I noticed that the green box for collision volumes in the editor is missing up until I re-enable it manually, but the code
tarGameObject.collider2D.enabled = false; tarGameObject.collider2D.enabled = true;
does not appear to work.
I don't know if this will help you in your situation, but this is what I have done in a similar case:
Object A collides with object B, Object A becomes the parent of Object B.
Object B's rigidbody is set to is$$anonymous$$inematic and it's collider is set to false (only because I need to enable it in the future )
Resize Object A's collider to envelope both objects.
Now they should both be influenced by only the one collider. Hope that helps
I really would prefer that each object have its own collider. A & B each have their own set of behaviors, and it would be prohibitive to have to write code to handle that. I have tried setting the child object's rigidbody to kinimatic, but I get bizzare result when the parent object rotates.
Right, I had troubles with what you're dealing with myself. I tried using a Fixed Joint, but there was too much movement in the joint, so I had to do what I mentioned above to resolve the issue as nothing else was working. I'm looking forward to seeing if someone has a different solution. One other option was a configurable joint and customizing that to, in my case, not rotate by means of the joint at all, but I found that it was way to robust a feature for what I needed. Hope you find something and if you find it yourself without someone answering, post it as an answer as I'm sure I wouldn't be the only one interested in hearing about it.
Your answer
Follow this Question
Related Questions
Why do GameObjects need Rigidbodies to collide? 0 Answers
Simple Rigidbody2D movement and jump 0 Answers
Why doesn't my hexagonal collision fit properly? 1 Answer
OnCollision2D never worked 0 Answers
Best solution for making arc collider 0 Answers