I'm making a 2D endless runner game that inspired by Dino Google Game.
I put PlatformSpawner outside to right of camera view. Then I put PlatformSpawner.cs into it. I made some prefabs called "Platform 01/02/03" etc that includes(empty-parent, child-sprite). Anyway, there is also Rope prefabs that connects Platform prefabs.
PlatformSpawner spawns them, and Platform Parent(empty in the scene) stores them.
Here is the scheme I wanted .enter image description here
Platform Prefabs;
Parent: Empty(Platform.cs, Box Cold 2D)
Child: aa(Sprite Renderer)
Rope Prefabs:
Parent: Empty(Rope.cs)
Child: cc(Sprite Renderer)
I have tried everything but never came close to good result. Is there anyone who can help?
using UnityEngine;
public class PlatformSpawner : MonoBehaviour
{
[SerializeField] private GameObject[] platformPrefabs;
[SerializeField] private Transform platformParent;
public float platformSpawnTime = 2f;
[Range(0, 1)] public float platformSpawnTimeFactor = 0.1f;
public float platformSpeed = 1f;
[Range(0, 1)] public float platformSpeedFactor = 0.2f;
private float _platformSpawnTime;
private float _platformSpeed;
private float timeAlive;
private float timeUntilPlatformSpawn;
private void Start()
{
GameManager.Instance.onGameOVer.AddListener(ClearPlatforms);
GameManager.Instance.onPlay.AddListener(ResetFactors);
}
private void Update()
{
if (!GameManager.Instance.isPlaying) return;
timeAlive += Time.deltaTime;
CalculateFactors();
SpawnLoop();
}
private void SpawnLoop()
{
timeUntilPlatformSpawn += Time.deltaTime;
if (timeUntilPlatformSpawn >= _platformSpawnTime)
{
Spawn();
timeUntilPlatformSpawn = 0f;
}
}
private void ClearPlatforms()
{
foreach (Transform child in platformParent)
Destroy(child.gameObject);
}
private void CalculateFactors()
{
_platformSpawnTime = platformSpawnTime / Mathf.Pow(timeAlive, platformSpawnTimeFactor);
_platformSpeed = platformSpeed * Mathf.Pow(timeAlive, platformSpeedFactor);
}
private void ResetFactors()
{
timeAlive = 1f;
_platformSpawnTime = platformSpawnTime;
_platformSpeed = platformSpeed;
timeUntilPlatformSpawn = 0;
}
private void Spawn()
{
GameObject prefab = platformPrefabs[Random.Range(0, platformPrefabs.Length)];
GameObject spawned = Instantiate(prefab, transform.position, Quaternion.identity);
spawned.transform.SetParent(platformParent, true);
Platform mover = spawned.GetComponent();
mover.Init(_platformSpeed);
}
}
using UnityEngine;
public class Platform : MonoBehaviour
{
private float speed;
private float destroyXPosition = -20f;
public void Init(float moveSpeed)
{
speed = moveSpeed;
}
private void Update()
{
transform.position += Vector3.left * speed * Time.deltaTime;
if (transform.position.x < destroyXPosition)
Destroy(gameObject);
}
}
using UnityEngine;
public class Rope : MonoBehaviour
{
//nothing
}
I have also added a GroundStart(Black One), it just stays there to make sure to player not to fall at the start. It moves to left with a simple code. Red dot is PlatformSpawner.