Search code examples
c#unity-game-enginegameobject

Unity2D C# Randomly Spawn GameObject in an Area over another GameObject


I'm new to Unity2D (Unity 5.0.2f1) and have been searching for a solution which I'm sure is staring me in the face!

I have a game object (essentially a road) like below (DirtTrack1):

enter image description here

I have a spawner which spawns GameObjects (vehicles). I want to spawn those vehicles over this road.

I have tried the following code to do this, essentially trying to spawn the vehicle within the Y-axis area of the road by getting the bottom Y co-ordinate of the road and the top Y co-ordinate, so I get the min and max vertical positions of where I can place the vehicle:

void FixedUpdate() {

    // Repeat spawning after the period spawn
    // route has finished.
    if (!_inSpawningIteration)
        StartCoroutine (SpawnVehiclePeriodically());
}

IEnumerator SpawnVehiclePeriodically()   
{
        // First, get the height of the vehicle and road.
        float vehicleHeightHalf = vehiclePreFab.GetComponent<SpriteRenderer>().bounds.size.y / 2f;
        float roadHeightHalf = roadObject.GetComponent<SpriteRenderer>().bounds.size.y / 2f;

        float roadTopY = roadObject.transform.position.y + roadHeightHalf;
        float roadBottomY = roadObject.transform.position.y - roadHeightHalf;

        // Next, ensure that maxY is within bounds of this farm vehicle.
        roadMaxY = roadTopY - vehicleHeightHalf;
        roadMinY = roadBottomY + vehicleHeightHalf;

    // Set the position and spawn.
    Vector3 newPosition = new Vector3 (Const_RoadItemsPositionX, randomY, 0f);
    GameObject vehicle = (GameObject)GameObject.Instantiate (vehiclePreFab, newPosition, Quaternion.identity);
}

This does spawn randomly but most times it is always not within the road itself. It is either part on the road or at the outside edge of it.

I can't figure out what I'm doing wrong here but I'm sure it is something very simple!


Solution

  • Tick the kinematic check of your vehicle, physics may be moving it out of the road if you don't do that.