Reputation: 2649
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?
Upvotes: 4
Views: 5687
Reputation: 1573
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);
Upvotes: 5