5.6 Designing Hazards and Obstacles

Hazards and obstacles make the game more challenging and engaging.

Step 1: Create a Hazard Object

  1. Add a 3D or 2D object (e.g., spikes or a rolling boulder).
  2. Add a Collider component.

Step 2: Create a Hazard Script
Attach this script to the hazard object:

void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.CompareTag("Player")) {
        Debug.Log("Player hit a hazard!");
    }
}

Step 3: Reset Player Position on Collision
Modify the script to reset the player:

void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.CompareTag("Player")) {
        collision.gameObject.transform.position = new Vector3(0, 2, 0);  // Reset position
    }
}