MONSTER TRUCK 2

A level where monster trucks drive by themselves across the screen, and players ride them or avoid them.

THE LEVEL

In Monster Truck 2, huge trucks cross the level without anyone pressing a button. They are real physics objects, built from a body and two wheel joints, so they bump, tip and crush. The challenge is to read where the next truck comes from and use it as a moving platform before it flattens you.

The first monster truck levels use a truck that a player starts with a button. For level 2 I wanted the trucks to keep coming on their own, so I built a second prefab driven by MonsterTruckStartBoost.

ENDLESS SPAWNING

The spawn point is a trigger box. When a truck leaves it, the next truck is created at the spawn position and moved into the active scene, so it belongs to the level that is really running.

// HandleMonsterTruckSpawnRequest: a trigger box around the spawn point.
// When a truck drives out of it, the next one is created. The stream never stops.
private void OnTriggerExit2D(Collider2D other)
{
    if (other.CompareTag("MonsterTruck"))
    {
        var obj = Instantiate(_monsterTruckPrefab, _spawnPoint.transform.position, Quaternion.identity);
        var targetScene = SceneManager.GetActiveScene();
        if (!targetScene.isLoaded) return;
        SceneManager.MoveGameObjectToScene(obj, targetScene);
    }
}

THE AUTOMATIC DRIVE

A WheelJoint2D has a motor with a speed and a maximum torque. The truck waits half a second, then starts with a strong motor and blends down to its cruising values. The same code drives forward and backward trucks, only the sign changes.

// MonsterTruckStartBoost: the truck drives itself, no button.
// After a short delay the motors start strong and settle to cruising speed.
private IEnumerator StartBoost()
{
    _boostTimeElapsed = 0;
    yield return new WaitForSeconds(0.5f);

    while (_boostTimeElapsed < _boostDuration)
    {
        _boostTimeElapsed += Time.deltaTime;
        var t = Mathf.Clamp01(_boostTimeElapsed / _boostDuration);
        var currentMotorSpeed = Mathf.Lerp(_motorStartBoost, _motorSpeed, t);
        var currentMaxTorque = Mathf.Lerp(_maxStartBoostTorque, _maxTorque, t);

        var frontMotor = _wj2dFrontTire.motor;
        var backMotor = _wj2dBackTire.motor;
        frontMotor.motorSpeed = _isGoingForward ? currentMotorSpeed : -currentMotorSpeed;
        backMotor.motorSpeed = _isGoingForward ? currentMotorSpeed : -currentMotorSpeed;
        frontMotor.maxMotorTorque = currentMaxTorque;
        backMotor.maxMotorTorque = currentMaxTorque;

        _wj2dFrontTire.motor = frontMotor;
        _wj2dBackTire.motor = backMotor;

        yield return new WaitForFixedUpdate();
    }
}

Limiting the wheel spin

Strong motors make wheels spin too fast, which breaks the physics. SetMaxAngularVelocity caps the spin of each wheel. I added an optional override on top of it, so the boost can allow a higher cap for a moment.

// SetMaxAngularVelocity: a wheel can never spin faster than its cap.
// The cap can be temporarily replaced by an override, then cleared.
private float? _maxAngularVelocityOverride;
public float CurrentMaxAngularVelocity => _maxAngularVelocityOverride ?? _maxAngularVelocity;

public void SetMaxAngularVelocityOverride(float value) => _maxAngularVelocityOverride = Mathf.Max(0f, value);
public void ClearMaxAngularVelocityOverride() => _maxAngularVelocityOverride = null;

RIDING A TRUCK

The truck reacts to collisions: it keeps its motors on while something touches it, and it makes the players on top its children so they stay on the platform while it moves.

// MonsterTruckCollisionBehavior: the truck is a moving platform.
// Anything standing on it becomes its child, so it is carried along.
private void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.TryGetComponent<PlayerPawn>(out var playerPawn))
    {
        playerPawn.transform.SetParent(transform);
    }
}

private void OnCollisionExit2D(Collision2D other)
{
    if (other.gameObject.TryGetComponent<PlayerPawn>(out var playerPawn))
    {
        playerPawn.transform.SetParent(playerPawn.GetOwner().transform);
    }
}

BUGS I FIXED

Physics levels break in surprising ways. These four fixes are the ones I remember the most from Monster Truck 2.

Wheels spinning the wrong way

The speed cap overwrote the wheel's angular velocity with a positive number. A truck driving backward has a negative spin, so the cap flipped its direction. The fix clamps the size of the spin and keeps the sign.

// BUG: the cap was applied as a positive number. A truck going backward spins its wheels
// the other way, so hitting the cap flipped the wheel spin direction.
// FIX: clamp the size of the spin, but keep its sign.
var maxAngularVelocity = CurrentMaxAngularVelocity;
_currentAngularVelocity = Mathf.Abs(_rb2d.angularVelocity);
if (_currentAngularVelocity >= maxAngularVelocity)
{
    _rb2d.angularVelocity = Mathf.Sign(_rb2d.angularVelocity) * maxAngularVelocity;
}
A boost that never ends

To make the level easier, trucks get a higher wheel cap during the start boost, which falls back to the normal cap. If the script is disabled halfway, the wheels would keep the high cap. OnDisable now always returns the wheels to their own cap.

// "Easier monster truck 2": the wheels get a higher spin cap while the boost lasts,
// and it falls back to each wheel's own cap over the boost duration.
private void SetBoostAngularVelocity(SetMaxAngularVelocity cap, float t)
{
    if (cap == null) return;

    cap.SetMaxAngularVelocityOverride(Mathf.Lerp(_boostMaxAngularVelocity, cap.MaxAngularVelocity, t));
}

// BUG: if the boost was cut short, the wheels could keep the boost cap forever.
// FIX: always hand the wheels their own cap back, even when the component is disabled.
private void OnDisable()
{
    ClearBoostAngularVelocity();
}
Trucks leaking into the next level

Trucks are spawned at runtime, so nothing in the level removes them. Each truck listens to the level loader and destroys itself before the next level loads.

// BUG: a truck still alive when the next level loads would leak into it.
// FIX: every truck destroys itself right before a level is loaded.
private void Awake()
{
    if (LevelLoader.IsInstanced)
    {
        LevelLoader.Instance.beforeLevelLoaded.AddListener(BeforeLevelLoaded);
    }
}

private void BeforeLevelLoaded(LevelInfo arg0)
{
    Destroy(gameObject);
}
Players destroyed with the truck

Because players become children of the truck they ride, destroying the truck could take them with it. When a truck is destroyed, every active player is given back to their own controller.

// BUG: players standing on a truck are its children. If the truck is destroyed
// (a new one spawns, a level ends), they would be destroyed or stuck with it.
// FIX: when a truck dies, give every player back to their own controller.
private void OnDestroy()
{
    foreach (var playerController in PlayersManager.Instance.GetActivePlayerControllers())
    {
        playerController.GetPlayerPawn().transform.SetParent(playerController.transform);
    }
}

The last fixes were about readability and feel: the trucks spawning could not be seen on screen, and dead players could not be pushed enough. I fixed both in the level and the truck prefab, with no new code.