Kill Zones
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 19 of 71.
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
EasyGive the player respawns. This script is on the player, so it moves transform and body, not other.
- In
Start(), set theVector3 respawnfield totransform.position. - In
OnTriggerEnter(Collider other), whenother.CompareTag("Checkpoint"), setrespawn = transform.position;. - When
other.CompareTag("KillZone"), settransform.position = respawn;andbody.linearVelocity = Vector3.zero;.
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.
}
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