Busier Rows
Lesson 12 of 20 in Coddy's Unity Game: Sky Lanes course.
One obstacle a row is easy: the other two lanes are always free. Later in the run, rows should hold two or three. made already counts the pieces, so it can set how busy a row may be:
int busy = Mathf.Min(3, 1 + made / 12);
int count = Random.Range(1, busy + 1);Two obstacles must not share a lane. Keep the free lanes in a list and take each one out once it is used. And three walls in a row would leave no way past, so at two walls pick a barrier or a bar instead.
List<int> lanes = new List<int> { -1, 0, 1 };
int pick = Random.Range(0, lanes.Count);
int lane = lanes[pick];
lanes.RemoveAt(pick);Challenge
Medium- In
Fill, work outbusyandcountas above. - Place
countobstacles, each in a lane taken out oflanes. - Count the walls; when
kind == 2and there are already two, pickRandom.Range(0, 2)instead.
Try it yourself
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public float laneSpeed = 16f;
public float jumpHeight = 1.6f;
public float gravity = -40f;
public float slideTime = 0.7f;
public int lane;
private CharacterController controller;
private GameManager game;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
game = FindFirstObjectByType<GameManager>();
}
void Update()
{
if (!game.over)
{
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);
bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
StopSlide();
}
if ((Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) && controller.isGrounded)
{
slide = slideTime;
Resize(0.5f);
}
}
if (slide > 0f)
{
slide -= Time.deltaTime;
if (slide <= 0f) StopSlide();
}
if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;
float targetX = lane * laneWidth;
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
Vector3 move = new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f);
controller.Move(move);
}
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}
void Resize(float height)
{
controller.enabled = false;
transform.position += Vector3.up * (height - transform.localScale.y);
transform.localScale = new Vector3(1f, height, 1f);
controller.enabled = true;
}
void OnTriggerEnter(Collider other)
{
if (game.over) return;
if (other.CompareTag("Obstacle"))
{
game.GameOver();
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Game: Sky Lanes
Practice on your own: Unity playground