- Home /
The random generated obstacles spawn outside the game platform
I'm making this game where a cube goes forward on a platform, and it has to dodge the obstacle (which are others cube) that are generated in a random way:
public class BlockSpawner : MonoBehaviour
{
public Transform[] spawnPoints;
public GameObject blockPrefab;
public float timeBetweenWaves = 1f;
private float timeToSpawn = 2f;
// Update is called once per frame
void Update()
{
if(Time.time >= timeToSpawn)
{
SpawnBlock();
timeToSpawn = Time.time + timeBetweenWaves;
}
}
void SpawnBlock()
{
int randomIndex = Random.Range(0, spawnPoints.Length);
for (int i = 0; i < spawnPoints.Length; i++)
{
if (randomIndex != i)
{
Instantiate(blockPrefab, spawnPoints[i].position, Quaternion.identity);
}
}
}
}
at the start, my problem was that the block spawners didn't move, so I made that the block spawners follow the player but 100z before it. Now the new problem is that the obstacle spawners change their X and fell off the platform, how do I fix their X position even when the player is moving right and left?
Answer by ADiSiN · May 07, 2020 at 03:20 PM
Hi!
To make sure that your object doesn't fall from platform you can clamp their position. For example, when your player is moving and therefore is spawner before actually assigning new position to spawner you clamp it's position to max and min value to make sure that the position will not be outside acessible.
To do that use Mathf.Clamp function and here is documentation about it that should help you further: https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
knockback 3d c# 1 Answer
Unity 2D Platfomer Enemy follow player only on x-axis, c# 1 Answer
Sprite sheet sprites into a material 0 Answers