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
MediumStart Arena Escape: the player slides on forces.
- In
Start(), after theGetComponentline, setrb.linearDamping = accel / topSpeed;, so it levels off neartopSpeed. - In
FixedUpdate(), buildnew Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")). - Pass its
normalizedtimesacceltorb.AddForcewithForceMode.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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground