Home > Software design >  How to create an object depending on the position of the player along the Y axis?
How to create an object depending on the position of the player along the Y axis?

Time:03-15

The game is an endless runner, in the game the player starts to go down the slope and it new obstacles should now appear lower in the coordinate, but I still have no idea how to do this.

    Instantiate(obj, new Vector3(20.46f, transform.position.y, 0), Quaternion.identity);

CodePudding user response:

hi you can use transform.UP vector to get the upward direction to your player. use it like this: newpos=transform.position (transfom.up*5); 5 is upward space to player.

CodePudding user response:

You should create a Vector 3 variable for your next position of terrain/tiles.

 private Vector3 _nextTerrainPos;

In your update method/ or LateUpdate method you can check if the position of your player is greater than the terrain and then you can generate more terrain like I have done below:

 if (Player.position.y > _nextTerrainPos.y) 
        {
            _nextTerrainPos.y  = 1000;
            a= Random.Range(0, 10);
            _nextTerrainPos.x = 0;
            GenerateNextTerrain2D(new Vector2(_nextTerrainPos.x, _nextTerrainPos.y));
        }

This is how you can instantiate your level and terrain:

GenerateNextTerrain2D(Vector terrainPos)
newTerrainObj = Instantiate(your level, _nextTerrainPos, Quaternion.identity) as GameObject;
        newTerrainObj.SetActive(true);
        //Camera.main.transform.position = new Vector3(117.4f,252.1f);
        //Camera.main.orthographicSize = 46f;
        DistanceHandler(newTerrainObj);

Here you can define the distance that has been covered:

public void DistanceHandler(GameObject tileset)
{
    if (VehicleSimpleControl.DistanceCovered >= 500)
    {
        tileset.transform.GetChild(0).gameObject.SetActive(true);
        
    }
    if (VehicleSimpleControl.DistanceCovered >= 700)
    {
        tileset.transform.GetChild(1).gameObject.SetActive(true);

    }
    if (VehicleSimpleControl.DistanceCovered >= 900)
    {
        tileset.transform.GetChild(2).gameObject.SetActive(true);

    }
    if (VehicleSimpleControl.DistanceCovered >= 1100)
    {
        tileset.transform.GetChild(3).gameObject.SetActive(true);

    }
}
  • Related