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

// GDnD wiki example
// Demonstrates: a drifting, size-tiered object that reports a hit so the field can split it
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[csharp-enums]]
 
using UnityEngine;
 
// An asteroid drifts in a straight line (wrapping via ScreenWrap2D) and carries a
// size tier. It does not split itself — it tells the field, which spawns the
// fragments. Keeping the spawn logic in one place is what makes the recursive
// split easy to read.
public class Asteroid : MonoBehaviour
{
    public enum Size { Large, Medium, Small }
 
    private AsteroidsGame field;
    private Vector2 velocity;
 
    public Size CurrentSize { get; private set; }
 
    public void Configure(AsteroidsGame owner, Size size, Vector2 driftVelocity, float scale)
    {
        field = owner;
        CurrentSize = size;
        velocity = driftVelocity;
        transform.localScale = Vector3.one * scale;
    }
 
    private void Update()
    {
        transform.position += (Vector3)(velocity * Time.deltaTime);
    }
 
    public void Hit()
    {
        field?.OnAsteroidHit(this);
    }
}