Slide
Lesson 4 of 20 in Coddy's Unity Game: Sky Lanes course.
Some obstacles hang too high to jump: the runner slides under them. A slide makes the runner half as tall for a moment.
Shrinking the object also shrinks its CharacterController, but it shrinks around the middle, so the feet would float half a unit above the road. Move the runner down by the same half unit. A controller must be off while you move it by hand, or its next Move undoes the change:
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;
}A timer, slide, counts the slide down. When it runs out the runner stands up again with StopSlide:
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}Challenge
Easy- Add
public float slideTime = 0.7f;andprivate float slide;. - Add
ResizeandStopSlideas above. - When S or the down arrow is pressed on the ground, set
slide = slideTimeand callResize(0.5f). - Each frame, if
slide > 0f, takeTime.deltaTimeoff it, and callStopSlide()once it reaches 0. - A jump ends a slide: call
StopSlide()when the runner jumps.
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 int lane;
private CharacterController controller;
private float fallSpeed;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
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);
}
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);
}
}
All lessons in Unity Game: Sky Lanes
Practice on your own: Unity playground