jeudi 9 juillet 2020

Problem with random spawning objects in Unity2d | Random spawning Unity2D

Hey I'm making a platformer. Where is random spawning of objects. It's spawn to the right side of the last platform. Here is the code

private void Spawn()
{
    //pos of topRightCorner
    bounds = lastP.platform.GetComponent<BoxCollider2D>().bounds;
    topRight = new Vector2(bounds.center.x + bounds.extents.x, bounds.center.y + bounds.extents.y);

    //spawn
    newP.platform = Instantiate(gO, Vector3.zero, new Quaternion());
    newP.index = lastP.index + 1;

    //position
    float randomX = Random.Range(5, spaceRangeX);
    float randomY = Random.Range(-spaceRangeY, spaceRangeY);

    Debug.Log("Generate: " + randomX + " " + randomY);

    newP.platform.transform.position = topRight + new Vector2(randomX, randomY);

    Debug.Log("new pos: " + topRight + new Vector2(randomX, randomY));

    Debug.Log(topRight + "-Top right");

    lastP.index = newP.index;
    lastP.platform = newP.platform;

    
}``
void Start()
{
    lastP.platform = Instantiate(gO, Vector3.zero, new Quaternion());
    lastP.index = 0;
    Spawn();
}
void Update()
{
    if(lastP.index != 7)
    {
        Spawn();
    }
    

}

And the class of my platforms

public struct Platform

{

public GameObject platform;
public int index;

} That's working good but the last platform spawning not far from the first platform Image




Aucun commentaire:

Enregistrer un commentaire