Positioning a prefab correctly with Instantiate
Hi,
A couple of month ago I started programming a little FPS in Unity with a friend of mine. One of our most disturbing challenges is the correct positioning of game objects.
Lets say we position two cubes on top of each other. Each cube has its own box collider and a rigidbody. Our goal is to shoot a them and each cube works with its own physics. The two cubes are positioned directly on our playground (which is a large cube (10,1,10)). While placing the two cubes manually, we don't have a problem:
The problem comes when saving the cube as prefab and then instantiating one cube on top of each other. Lets say I have a Loop and instantiate first cube #1 and then instantiate the 2nd cube in my 2nd pass of the loop (y + 1). This should position both cubes correctly....
But what happens is: The upper cube flies away....like two magnets having the same polarity.
Why does this happen? I would think that while instantiating those two cubes, a collision happens and physics do the rest....
Is there a logic explanation? In our future project we will have a lot game objects on top of each other.
Thanks for any helping hands.
Best regards, Eyanosa
Answer by jtok4j · Oct 22, 2017 at 07:31 PM
Greetings, I've noted that when I begin a scene, with the player Gameobject's collider intersects the Terrain's collider (e.g. placed the Player a little to close/slightly into the ground) then the Player flies around, upon starting the game. So, possibly, the colliders of the cubes are intersecting each other, and should be examined. Hope this helps.
Answer by the_real_ijed · Jan 17, 2018 at 08:57 PM
Yes, the above post is correct - if the cubes are instantiated as touching then the physics system will fire them off away from each other. I'm guessing the bottom one doesn't because of the floor. Just instantiate them both a bit higher up and with a slight gap between them so they aren't touching each other or the floor when created.
Bear in mind this quirk of physics engines can be a useful if you want to make an explosion of debris :)