Question by
IvayloDev · Aug 19, 2016 at 05:53 AM ·
spritespawninggenerationwidth
Spawn objects with different widths one after another without overlapping
I need to generate background of buildings (I have an array of 5 sprites) and want to spawn each one right after the last one.
This is my current code.
for (int i = 0; i < 5; i++) {
Sprite sprite = BuildingsSprites[Random.Range(0, 5)];
float currentWidth = sprite.bounds.size.x;
GameObject Background = (GameObject)Instantiate(BuildingObjectPrefab, nextPos, Quaternion.identity);
Background.GetComponent<SpriteRenderer>().sprite = sprite;
nextPos += new Vector3(currentWidth / 2, 0, 0);
Sprite nextSprite = BuildingsSprites[Random.Range(0, 5)];
float nextWidth = nextSprite.bounds.size.x;
GameObject Background2 = (GameObject)Instantiate(BuildingObjectPrefab, nextPos, Quaternion.identity);
Background2.GetComponent<SpriteRenderer>().sprite = nextSprite;
nextPos += new Vector3(nextWidth / 2, 0, 0);
}
I cant seem to fix the problem which is in the last line, nextPos is set to nextWidth but when the loop goes to the top It may choose different sprite with different width and its placed not where it was supposed to.
Comment
Best Answer
Answer by IvayloDev · Aug 19, 2016 at 04:09 PM
Found the way!
float prevWidth = 1;
Vector3 nextPos = BuildingsPos;
for (int i = 0; i < 25; i++) {
Sprite sprite = BuildingsSprites[Random.Range(0, 5)];
float currentWidth = sprite.bounds.size.x;
nextPos += new Vector3(currentWidth / 2 + prevWidth / 2, 0, 0);
GameObject Background = (GameObject)Instantiate(SpawnedObjectHolder, nextPos, Quaternion.identity);
Background.GetComponent<SpriteRenderer>().sprite = sprite;
prevWidth = currentWidth;
}
Your answer
Follow this Question
Related Questions
Random Layout of tiles notworking in 2d game 1 Answer
Enemy Spawner 2 Answers
Spawning Path 0 Answers
[C#] Issue with calculating transform.position and Vector2D 1 Answer
How to check that a sprite button is the same as another sprite button? 0 Answers