- Home /
Question by
Zzz24 · Sep 21, 2020 at 10:08 PM ·
c#unity 2dgameobjectsinstantiate prefabgames
Instantiate random platforms
Hi everyone,
I'm creating a 2D infinite jumping mobile game and following a couple of tutorials.
I have been able to instantiate platforms randomly once the camera reaches the generation point, but at the moment they are in a fixed position on the x axis using the following code:
using System.Collections;
using UnityEngine;
public class PlatformGenerator : MonoBehaviour
{
public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;
private float platformWidth;
public float distanceBetweenMin;
public float distanceBetweenMax;
void Start()
{
platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;
}
void Update()
{
if (transform.position.x < generationPoint.position.y)
{
distanceBetween = Random.Range(distanceBetweenMin, distanceBetweenMax);
transform.position = new Vector3 (transform.position.x + platformWidth, transform.position.y + platformWidth + distanceBetween, transform.position.z);
Instantiate(thePlatform, transform.position, transform.rotation);
}
}
}
This seems to be the only piece of code that instantiates platforms without them overlapping one another every time.
I have tried to change the position on the x axis but have only been able to get them to veer to the right and eventually off screen by adding distanceBetween to the transform.position.x in Vector3.
Is there a way to randomise the platforms on the x axis without them veering in one direction?
Please and thank you in advance :)
Comment