Source file unity-csharp/arcade-classics/frogger/Hazard.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: a lane hazard that slides at a fixed velocity and despawns once it leaves the screen
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[unity-transform]]
 
using UnityEngine;
 
// One car or log. It moves at a constant velocity set by its lane and removes
// itself when it has fully crossed the screen. Logs expose their velocity so the
// frog can be carried along while riding one.
public class Hazard : MonoBehaviour
{
    [SerializeField] private float despawnMargin = 1.5f;
 
    public Vector2 Velocity { get; private set; }
 
    private Camera cachedCamera;
 
    private void Awake()
    {
        cachedCamera = Camera.main;
    }
 
    public void Launch(Vector2 velocity)
    {
        Velocity = velocity;
    }
 
    private void Update()
    {
        transform.position += (Vector3)(Velocity * Time.deltaTime);
 
        float halfWidth = cachedCamera.orthographicSize * cachedCamera.aspect;
        bool goneRight = Velocity.x > 0f && transform.position.x > halfWidth + despawnMargin;
        bool goneLeft = Velocity.x < 0f && transform.position.x < -halfWidth - despawnMargin;
 
        if (goneRight || goneLeft)
        {
            Destroy(gameObject);
        }
    }
}