Steer
Lesson 2 of 14 in Coddy's Unity Game: Snake 3D course.
The snake turns with the arrow keys or WASD. The camera looks down at the board from the front edge, so up the screen is along +z, Vector3.forward, and down is Vector3.back. Vector3.up points at the sky: a head moved by it would rise off the board.
A turn happens once per press, so read the keys with wasPressedThisFrame. The press only changes direction; Step() still moves the head, on the next tick:
Keyboard keyboard = Keyboard.current;
if (keyboard != null && keyboard.dKey.wasPressedThisFrame)
{
direction = Vector3.right;
}An arrow and its letter are two keys, joined with ||. Keyboard.current is null on a device with no keyboard, so check it once at the top.
Challenge
EasySteer the snake with the arrows or WASD.
- Add
using UnityEngine.InputSystem;toSnake. - At the top of
Update(), readKeyboard.current: up or W setsdirection = Vector3.forward, down or SVector3.back, left or AVector3.left, right or DVector3.right. - Leave
Step()as it is: the head turns on the next tick.
Press Play, click the game and steer: the head turns on the next step. Then Check.
Try it yourself
using UnityEngine;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // seconds between two steps
private float timer;
private Vector3 direction = Vector3.right;
void Update()
{
timer += Time.deltaTime;
if (timer >= tick)
{
timer -= tick;
Step();
}
}
void Step()
{
transform.position += direction;
}
}
All lessons in Unity Game: Snake 3D
Practice on your own: Unity playground