Menu
CoddyTech

Kill Zones

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 18 of 63.

A kill zone is a trigger over a place the player must not reach: lava, spikes, or the empty space under the level. Entering it sends the player back to a spawn point. Here the lava's own script does it, with the spawn point in a Transform field set in the Inspector:

public Transform spawnPoint;

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        other.transform.position = spawnPoint.position;
        other.attachedRigidbody.linearVelocity = Vector3.zero;
    }
}

other.attachedRigidbody is the Rigidbody the entering collider belongs to. Setting transform.position teleports the player, which is what a respawn needs. A Rigidbody keeps its velocity through the jump, though: a player who fell in at 10 units per second arrives at the spawn point still falling at 10, and one who ran into the lava keeps running, straight back in. Setting linearVelocity to Vector3.zero makes it arrive standing still. The tag check leaves anything else that falls into the lava where it is.

challenge icon

Challenge

Easy

The player crosses a narrow bridge over the void, pushed with forces by the arrow keys; that part is written. A trigger tagged KillZone fills the space below, and a flag tagged Checkpoint, also a trigger, stands halfway along the bridge. Give the player's script respawns:

  • When the game starts, the respawn point is where the player stands.
  • Touching a Checkpoint makes the player's position at that moment the new respawn point.
  • Entering the KillZone puts the player back at the respawn point, standing still.

Press Play and walk off the bridge, then Check.

Try it yourself

using UnityEngine;

public class Player : MonoBehaviour
{
    public float force = 12f;
    Rigidbody body;
    Vector3 input;
    // respawn: where the player comes back

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

    void Update()
    {
        input = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    }

    void FixedUpdate()
    {
        body.AddForce(input * force);
    }

    // Checkpoint: remember where the player is. KillZone: back to that spot, standing still.
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay