Falling Obstacles
This tutorial will look at adding falling obstacles to your game that will reset once they’ve fallen a certain distance. These obstacles won’t collide with anything but the Player.
Example FallingObjects Code
using UnityEngine;
public class FallingObjects : MonoBehaviour
{
private Rigidbody2D rb;
private Vector3 startPosition;
[Range(5f, 50f)]
public float maxDistance = 15f; // distance before it resets
private void Start()
{
rb = GetComponent<Rigidbody2D>();
startPosition = transform.position;
}
private void Update()
{
// Check if the object has fallen too far from its start position
if (Vector3.Distance(transform.position, startPosition) > maxDistance)
{
transform.position = startPosition;
rb.velocity = Vector2.zero;
rb.angularVelocity = 0f;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.name == "Player")
{
other.GetComponent<ResetPlayer>().ResetToStart();
}
}
}