Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly spawn Gameobject exactly on top of another object?

Working on a 2D game in Unity and I'm having difficulties trying to spawn a block exactly on top of a platform in my game. I don't want the block to look like it's floating or overlapping the platform.

I can't seem to get the calculation correct.

I currently have this code:

public GameObject blockPrefab;
 public GameObject platform;
 public GameObject dummyBlock;

 // Use this for initialization
 void Start () 
 {
     float platformSize = platform.GetComponent<Renderer>().bounds.size.y;
     float blockSize = dummyBlock.GetComponent<Renderer>().bounds.size.y;
     Debug.Log(platformSize.ToString());


     GameObject test = (GameObject)Instantiate(blockPrefab,
                                               new Vector3(platform.transform.position.x, platform.transform.position.y + platformSize/2, platform.transform.position.z),
                                               Quaternion.identity);
 }

The problem with this is that it spawns the block in a way that it overlaps the platform which means my calculation for the block's y position is wrong.

I'm still getting used to working with Unity's world coordinate system, so yeah. Anybody know how to solve this?

like image 648
aresz Avatar asked Oct 14 '25 03:10

aresz


1 Answers

The Vector3 you pass to Instantiate will be the centre of the instantiated GameObject, but it looks like you're calculating where the bottom of it should be. Try adding half the of the block height to the y coordinate as well:

float platformTop = platform.transform.position.y + platformSize/2;
Vector3 blockCentre = new Vector3(platform.transform.position.x, platformTop + blockSize/2, platform.transform.position.z);
GameObject test = (GameObject)Instantiate(blockPrefab, blockCentre, Quaternion.identity);
like image 143
Adam H Avatar answered Oct 18 '25 14:10

Adam H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!