I am trying to instantiate 3 different prefab object platforms at random. These platforms have box colliders and rigid bodies ( is kinematic) attached to them. When they are instantiated their x and y positions are also random. These plat forms also move up/down or left/right. I am trying to figure out how to get them so they don’t instantiate on top of each other and so when they move, don’t collide/pass through the other platforms. Rigid body(with gravity) players land on the platforms,so I dont want them to fall through the platforms.
I am thinking that one would need to check the previously made platform x and then if the new randomly generated x is the same, randomly generate a new x, or something like this, though I am not sure how to do this with my code.
I am new to programming so please be specific in your answers (ie. If I need to add a line of code or take out a part please tell me exactly what to do) Any help would be greatly appreciated.
public class cEndless : MonoBehaviour {
public Transform player;
public float playerHeightY;
public Transform PlatAA;
public Transform PlatAB;
public Transform PlatAC;
private int platNum;
public int currentNumPlat; //Self-explained
public int maxNumPlat; //Self-explained
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag("Player").transform;
currentNumPlat = 0;
maxNumPlat = 3;
if (currentNumPlat == 0)
{
Vector2 posAB = new Vector2(0,0);
Instantiate (PlatAA, posAB, Quaternion.identity);
currentNumPlat += 1;
}
}
// Update is called once per frame
void Update () {
playerHeightY = player.position.y;
if (currentNumPlat < maxNumPlat)
{
PlatformSpawner();
}
}
void PlatformSpawner()
{
if (currentNumPlat < maxNumPlat)
{
platNum = Random.Range(1,4);
float x = Random.Range (-8, 8);
float y = Random.Range (playerHeightY + 1.3f, playerHeightY +3.3f);
Vector2 posXY = new Vector2 (x, y);
if (platNum == 1)
{
Instantiate (PlatAA, posXY, Quaternion.identity);
}
if (platNum == 2)
{
Instantiate (PlatAB, posXY, Quaternion.identity);
}
if (platNum == 3)
{
Instantiate (PlatAC, posXY, Quaternion.identity);
}
currentNumPlat += 1;
}
}
}
This approach achieves separation, but not cohesion, which I assumed was an implied requirement. If they wanted separation without cohesion, they could simply ensure no two platforms are within X distance of each other, where X is twice the greatest distance a platform can travel from its origin, and be done. In that case, it would be wasteful to use physics.OverlapSphere.
– AlwaysSunny