- Home /
Can anyone help me with my 2D endless runner overlapping platforms?
Hello! I'm a new Unity user, and a C# noob. I'm currently making a 2D endless runner in Unity and my platforms that I'm generating using object pools seem to want to overlap and bunch up no matter what I do.
In the picture above, the platforms should be at variable heights, but match up at their ends.
Below, I will post my code for the platform generator. It is sorta long, but I think the problem is near the end after my heightChange stuff. I really just need fresh eyes on this, as I have been frustrated for several days. Thanks in advance for any tips.
using UnityEngine;
using System.Collections;
public class PlatformGenerator : MonoBehaviour
{
public GameObject platform;
public GameObject[] platforms;
public Transform generationPoint;
public float distanceBetweenMin;
public float distanceBetweenMax;
public ObjectPooler[] objectPools;
public Transform maxHeightPoint;
public float maxHeightChange;
private float distanceBetween;
private float platformLength;
private float minHeight;
private float maxHeight;
private float heightChange;
private int platformSelector;
private float[] platformLengths;
// Use this for initialization
void Start ()
{
platformLength = platform.GetComponent<BoxCollider2D>().size.x;
platformLengths = new float[objectPools.Length];
for(int i = 0; i < objectPools.Length; i++)
{
platformLengths[i] = objectPools[i].pooledObject.GetComponent<BoxCollider2D>().size.x;
}
minHeight = transform.position.y;
maxHeight = maxHeightPoint.position.y;
}
// Update is called once per frame
void Update ()
{
if(transform.position.x < generationPoint.position.x)
{
distanceBetween = Random.Range(distanceBetweenMin, distanceBetweenMax);
platformSelector = Random.Range(0, objectPools.Length);
heightChange = transform.position.y + Random.Range(maxHeightChange, -maxHeightChange);
if(heightChange > maxHeight)
{
heightChange = maxHeight;
}else if(heightChange < minHeight)
{
heightChange = minHeight;
}
transform.position = new Vector3(transform.position.x + platformLengths[platformSelector] + distanceBetween, heightChange, 0);
GameObject newPlatform = objectPools[platformSelector].GetPooledObject();
newPlatform.transform.position = transform.position;
newPlatform.transform.rotation = transform.rotation;
newPlatform.SetActive(true);
transform.position = new Vector3(transform.position.x + platformLengths[platformSelector], transform.position.y, 0);
}
}
}
Your answer
Follow this Question
Related Questions
Endless Runner Overlapping Platforms Bug 0 Answers
4 C# errors Endless Runner 0 Answers
3D infinite runner game platform generation gives an error 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers