Menu
CoddyTech

The Arena

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 59 of 71.

This chapter builds Arena Escape. You dodge hunters in a walled arena while waves of them pour in, three hits end the run, and once the last wave is out an exit opens. The game is five scripts, in the project from the start: Player, Hunter, Spawner, Health and Exit. The last four are empty for now, and each lesson fills one in.

The player moves with forces instead of a velocity it sets, so a hunter's knockback adds to its movement instead of being wiped out. A push alone would speed it up for ever, so linearDamping takes a share of its speed off in every step: a steady push levels off at a top speed of about the acceleration divided by the damping. This hover sled pushes forward while Space is held:

[SerializeField] private float accel = 12f;
private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
    rb.linearDamping = 2f;
}

void FixedUpdate()
{
    if (Input.GetKey(KeyCode.Space))
    {
        rb.AddForce(transform.forward * accel, ForceMode.Acceleration);
    }
}

With an acceleration of 12 and a damping of 2, the sled tops out near 6 units per second, and when Space is let go the damping brings it to a stop instead of letting it glide for ever. ForceMode.Acceleration ignores the mass, so a heavy sled speeds up exactly like a light one. The sled's collider has a frictionless PhysicsMaterial: with friction from the floor on top of the damping, it would top out lower.

challenge icon

Challenge

Medium

Start Arena Escape: the player slides on forces.

  1. In Start(), after the GetComponent line, set rb.linearDamping = accel / topSpeed;, so it levels off near topSpeed.
  2. In FixedUpdate(), build new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")).
  3. Pass its normalized times accel to rb.AddForce with ForceMode.Acceleration.

Press Play and slide around the arena. Then Check.

Try it yourself

using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] private float accel = 18f;
    [SerializeField] private float topSpeed = 6f;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        // set the damping, then push the player with the arrows
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground