Files
grass-cutters/Assets/Scripts/Gameplay/Vehicle.cs
NiemandKG e186a7e883 Autopilot steers round what's in its way
A machine on autopilot looks a few metres ahead and swerves to the clearer side of a building, rock, person or
machine, so it goes round things instead of through them; it still touches nothing, so what it can't get round it
passes through, and it can't be wedged or tipped. It rolls over the deck rails. -demoauto counts swerves and hops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 20:25:01 +06:00

693 lines
34 KiB
C#

using System.Collections.Generic;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// A machine belongs to whoever bought it and takes their upgrades; anyone can ride it. E to hop on; the driver owns (and
/// simulates) the body. Rides on raycast springs over the soil, the deck and the ramp, mows the meadow under its cutter
/// while driving and unloads at a garage pad. The pickup carries bundles on its bed instead.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public partial class Vehicle : NetworkBehaviour, IInteractable
{
public static readonly List<Vehicle> All = new List<Vehicle>();
public const ulong Nobody = ulong.MaxValue;
public VehicleKind kind;
public Transform seat, intake, wake, bars, arm, fill, fanL, fanR, reel, chute;
public Transform[] wheels;
/// <summary>The towed part (a trailer, a baler) swings on this pin behind the tractor. The shell is the whole visible machine.</summary>
public Transform hitch, shell;
public float length = 2.8f, width = 1.1f;
public readonly NetworkVariable<ulong> Driver = new NetworkVariable<ulong>(Nobody);
public readonly NetworkVariable<float> Tank = new NetworkVariable<float>(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<float> Throttle = new NetworkVariable<float>(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<bool> Slurping = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Save key of the player it belongs to.</summary>
public readonly NetworkVariable<FixedString64Bytes> Crew = new NetworkVariable<FixedString64Bytes>();
/// <summary>Level of each upgrade, by <see cref="TuneId"/>.</summary>
public NetworkList<byte> Tuned { get; private set; }
/// <summary>What's on the bed: kind and kilos of each bundle.</summary>
public NetworkList<Vector2> Bed { get; private set; }
public Rigidbody Body { get; private set; }
public bool HasDriver => Driver.Value != Nobody;
public bool LocalDriving => IsSpawned && Driver.Value == NetworkManager.LocalClientId;
public Transform Seat => seat ? seat : transform;
bool _cruise;
float _steer, _armAngle, _fanSpin, _unloadCarry, _wakeT, _sprayT, _wheelSpin;
int[] _wheelAxis;
float[] _wheelWay;
bool[] _wheelFront;
Vector3[] _wheelRest;
float[] _wheelDrop;
/// <summary>Each tyre's own radius, from its mesh (its renderer's box swells as it turns).</summary>
public float[] WheelRadius { get; private set; }
int _reelAxis = -1;
AudioSource _engine, _suck;
static Transform s_dock;
TeamState Ts => TeamState.Instance;
public VehicleDef Def => GameDefs.Vehicle(kind);
public int Level(TuneId t) => Tuned != null && (int)t < Tuned.Count ? Tuned[(int)t] : 0;
public float Capacity => Def.bed > 0 ? Def.bed : Def.hopper * GameDefs.VehicleTankMul(Level(TuneId.Hopper));
/// <summary>What it's carrying, against <see cref="Capacity"/>.</summary>
public float Load => Def.bed > 0 ? Bed.Count : Tank.Value;
/// <summary>How wide the cutter on the model is (set by the builder); the strip is at least that.</summary>
public float barWidth;
/// <summary>Parts that fold in while it squeezes out of a shed door (a mulcher's wings).</summary>
public Transform[] fold;
public readonly NetworkVariable<bool> Folded = new NetworkVariable<bool>();
Vector3[] _foldRest;
float _folded;
public float CutWidth => Mathf.Max(Def.width, barWidth) * (1f + Level(TuneId.Cutter) * 0.25f);
public float TopSpeed => Def.speed * GameDefs.VehicleSpeedMul(Level(TuneId.Motors)) * GameDefs.CutterSpeed(Level(TuneId.Cutter));
public bool Cruising => _cruise;
/// <summary>The machine a player already has of this kind.</summary>
public static Vehicle Mine(VehicleKind kind, string crew)
{
foreach (var v in All) if (v && v.kind == kind && v.Crew.Value.ToString() == crew) return v;
return null;
}
void Awake()
{
Body = GetComponent<Rigidbody>();
Body.useGravity = false;
Tuned = new NetworkList<byte>();
Bed = new NetworkList<Vector2>();
if (seat) seat.position += transform.forward * Def.seatAhead - transform.up * Def.seatDrop;
}
public override void OnNetworkSpawn()
{
All.Add(this);
if (IsServer) while (Tuned.Count < (int)TuneId.Count) Tuned.Add(0);
_engine = Sfx.Loop(kind == VehicleKind.Tractor || kind == VehicleKind.Hauler || kind == VehicleKind.Baler ? "tractor_engine_loop" : kind == VehicleKind.Combine || kind == VehicleKind.Mulcher ? "combine_engine_loop" : kind == VehicleKind.Pickup ? "pickup_engine_loop" : "mower_engine_loop", transform, 0f);
_suck = Sfx.Loop("suck_loop", intake ? intake : transform, 0f);
}
public override void OnNetworkDespawn()
{
All.Remove(this);
if (_engine) Destroy(_engine.gameObject);
if (_suck) Destroy(_suck.gameObject);
}
public override void OnDestroy()
{
All.Remove(this);
base.OnDestroy();
}
// ───────────────────────── seat ─────────────────────────
public string Prompt => HasDriver ? null : OnAuto ? Loc.F("Take over the {0} ({1}, {2} / {3})", Def.name, AutoPrompt, GameDefs.Kilos(Tank.Value), GameDefs.Kilos(Capacity)) : Def.bed > 0 ? Loc.F("Ride the {0} ({1} of {2} bundles, E with a bundle loads it)", Def.name, Bed.Count, Def.bed) : Loc.F("Ride the {0} ({1} / {2})", Def.name, GameDefs.Kilos(Tank.Value), GameDefs.Kilos(Capacity));
public bool CanInteract => !HasDriver;
public void Interact()
{
if (!HasDriver) EnterRpc();
}
[Rpc(SendTo.Server)]
void EnterRpc(RpcParams rpc = default)
{
ulong who = rpc.Receive.SenderClientId;
if (HasDriver || RollingOut) return;
foreach (var v in All) if (v != this && v.Driver.Value == who) return;
Driver.Value = who;
// getting in takes it back from the autopilot
Auto.Value = (byte)AutoJob.Off;
_resumeAt = 0f;
if (OwnerClientId != who) NetworkObject.ChangeOwnership(who);
}
public void RequestExit() => ExitRpc();
[Rpc(SendTo.Server)]
void ExitRpc(RpcParams rpc = default)
{
if (Driver.Value != rpc.Receive.SenderClientId) return;
ServerEject();
}
public void ServerEject()
{
if (!IsServer) return;
Driver.Value = Nobody;
if (!IsOwnedByServer) NetworkObject.ChangeOwnership(NetworkManager.ServerClientId);
}
/// <summary>Server: a garage calls it over.</summary>
/// <summary>How far its tail reaches behind its middle along its own back, and how tall it stands, in metres (trailers included).</summary>
public void Extent(out float back, out float top, out float bottom)
{
back = 0.5f;
top = 0.5f;
bottom = 0f;
foreach (var r in GetComponentsInChildren<Renderer>())
{
var b = r.bounds;
for (int i = 0; i < 8; i++)
{
var c = b.center + Vector3.Scale(b.extents, new Vector3((i & 1) == 0 ? -1 : 1, (i & 2) == 0 ? -1 : 1, (i & 4) == 0 ? -1 : 1));
back = Mathf.Max(back, -Vector3.Dot(c - transform.position, transform.forward));
top = Mathf.Max(top, Vector3.Dot(c - transform.position, transform.up));
bottom = Mathf.Min(bottom, Vector3.Dot(c - transform.position, transform.up));
}
}
}
/// <summary>Everyone: out of sight for a moment (waiting in a shed behind a shut door that it doesn't fit behind).</summary>
public void HideFor(float seconds)
{
StartCoroutine(Hide(seconds));
}
System.Collections.IEnumerator Hide(float seconds)
{
var shown = new System.Collections.Generic.List<Renderer>();
foreach (var r in GetComponentsInChildren<Renderer>()) if (r.enabled) { r.enabled = false; shown.Add(r); }
yield return new WaitForSeconds(seconds);
foreach (var r in shown) if (r) r.enabled = true;
}
/// <summary>Server: true while it drives itself out of a shed (nobody can get on until it's out).</summary>
public bool RollingOut { get; private set; }
/// <summary>Server: wait inside a shed for the door, roll out to the pad, then let physics have it again.</summary>
public void ServerRollOut(Vector3 from, Vector3 to, Quaternion rot)
{
if (!IsServer) return;
StopAllCoroutines();
StartCoroutine(RollOut(from, to, rot));
}
System.Collections.IEnumerator RollOut(Vector3 from, Vector3 to, Quaternion rot)
{
RollingOut = true;
Folded.Value = fold != null && fold.Length > 0;
if (Body.isKinematic) Body.isKinematic = false;
ServerPut(from, rot);
Body.isKinematic = true;
yield return new WaitForSeconds(VehicleShed.Wait);
for (float t = 0f; t < 1f;)
{
t = Mathf.Min(1f, t + Time.fixedDeltaTime / VehicleShed.Drive);
float e = t * t * (3f - 2f * t);
Body.MovePosition(Vector3.Lerp(from, to, e));
yield return new WaitForFixedUpdate();
}
Body.isKinematic = false;
ServerPut(to, rot);
RollingOut = false;
Folded.Value = false;
}
public void ServerPut(Vector3 at, Quaternion rot)
{
Body.position = at;
Body.rotation = rot;
Body.linearVelocity = Vector3.zero;
Body.angularVelocity = Vector3.zero;
transform.SetPositionAndRotation(at, rot);
}
// ───────────────────────── the pickup's bed ─────────────────────────
[Rpc(SendTo.Server)]
public void LoadRpc(ulong bundle, RpcParams rpc = default)
{
if (Bed.Count >= Def.bed || !NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(bundle, out var no)) return;
var c = no.GetComponent<Cargo>();
if (!c || c.Grab.Consumed || c.Grab.Holder.Value != rpc.Receive.SenderClientId) return;
Bed.Add(new Vector2((int)c.kind, c.Kg.Value));
c.Grab.ServerForceRelease();
c.Grab.Consumed = true;
c.NetworkObject.Despawn(true);
}
/// <summary>T: tip everything out behind the machine.</summary>
[Rpc(SendTo.Server)]
public void TipRpc()
{
var back = -transform.forward;
for (int i = 0; i < Bed.Count; i++)
Spawner.Instance.SpawnCargo((CargoKind)(int)Bed[i].x, transform.position + back * (length * 0.5f + 0.6f + i * 0.7f) + transform.up * 1.2f, Quaternion.identity, back, Bed[i].y);
Bed.Clear();
}
void Update()
{
if (!IsSpawned) return;
if (LocalDriving)
{
// G at a garage: its screen, open on this machine's upgrades
if (Ctl.BootsPressed && VehicleShed.Near(transform.position) is VehicleShed near)
{
Sfx.Play("ui_open");
UIRoot.I?.OpenGarage(near.GetComponent<Garage>(), kind);
}
if (Ctl.CruisePressed && CanAuto)
{
AutoRpc();
Sfx.Play("ui_click", 0.8f, 1.2f);
Hud.Toast(Loc.F("Autopilot on: the {0} mows round here and unloads itself. Hop back in to take over.", Def.name), Hud.ToastKind.Info);
}
else if (Ctl.CruisePressed && Level(TuneId.Cruise) > 0) _cruise = !_cruise;
if (Ctl.MovePressed && Def.bed > 0) TipRpc();
}
else _cruise = false;
// the driver left the game
if (IsServer && HasDriver && !NetworkManager.ConnectedClients.ContainsKey(Driver.Value)) ServerEject();
Visuals();
Fold();
}
// ───────────────────────── physics (owner) ─────────────────────────
static readonly Vector2[] Probes = { new Vector2(-0.5f, 0.42f), new Vector2(0.5f, 0.42f), new Vector2(-0.5f, -0.42f), new Vector2(0.5f, -0.42f) };
void FixedUpdate()
{
if (!IsSpawned || !IsOwner || Body.isKinematic) { if (_ghost) Ghost(false); return; }
bool driving = LocalDriving;
var input = driving ? Ctl.Move : Vector2.zero;
// the host drives a machine on autopilot
bool auto = false;
if (IsServer && !HasDriver)
{
AutoResume();
if (OnAuto) { input = AutoInput(Time.fixedDeltaTime); auto = true; }
}
float boost = driving && Ctl.Sprint ? GameDefs.BoostMul(Level(TuneId.Turbo)) : 1f;
if (input.y < -0.1f) _cruise = false;
float throttle = _cruise && input.y < 0.1f ? 1f : input.y;
float dt = Time.fixedDeltaTime;
var up = Planet.Up(transform.position);
Body.AddForce(-up * GameDefs.LowGravity, ForceMode.Acceleration);
// on autopilot it touches nothing: it steers round things and goes through what it can't get round
Ghost(auto);
// raycast springs at four corners (soil, deck, ramp)
int wet = 0;
float g = GameDefs.LowGravity;
const float ride = 0.44f; // springs settle ~0.42 m under the target: wheels just touch the ground
int groundMask = (1 << Layers.Default) | (1 << Layers.Build);
for (int i = 0; i < Probes.Length; i++)
{
var local = new Vector3(Probes[i].x * width, 0f, Probes[i].y * length);
var wp = transform.TransformPoint(local);
float clearance = Planet.Altitude(wp);
if (_ghost) clearance = Mathf.Min(clearance, DeckClearance(wp, up, 1.2f + ride + 1.5f));
else if (Physics.Raycast(wp + up * 1.2f, -up, out var sh, 1.2f + ride + 1.5f, groundMask, QueryTriggerInteraction.Ignore))
clearance = Mathf.Min(clearance, sh.distance - 1.2f);
float depth = ride - clearance;
if (depth > 0f)
{
wet++;
var pv = Body.GetPointVelocity(wp);
float f = Mathf.Min(depth, 1.2f) * g * 2.4f - Vector3.Dot(pv, up) * 2.2f;
Body.AddForceAtPosition(up * f * Body.mass / Probes.Length, wp, ForceMode.Force);
}
}
bool onGround = wet > 0;
// drive
var fwd = Vector3.ProjectOnPlane(transform.forward, up).normalized;
var flatV = Vector3.ProjectOnPlane(Body.linearVelocity, up);
float fwdSpeed = Vector3.Dot(flatV, fwd);
if (onGround)
{
float accel = Def.accel * boost * GameDefs.VehicleSpeedMul(Level(TuneId.Motors));
float target = throttle * TopSpeed * boost * (throttle < 0f ? 0.4f : 1f);
float dv = Mathf.Clamp(target - fwdSpeed, -accel * dt, accel * dt);
Body.AddForce(fwd * dv * Body.mass / dt, ForceMode.Force);
// tyres grip sideways
var side = Vector3.Cross(up, fwd);
float sideSpeed = Vector3.Dot(flatV, side);
Body.AddForce(-side * sideSpeed * 5f * Body.mass, ForceMode.Force);
Body.AddForce(-flatV * 0.12f * Body.mass, ForceMode.Force);
// steering
_steer = Mathf.MoveTowards(_steer, input.x, dt * 4f);
float turnRate = Def.turn * Mathf.Clamp(Mathf.Abs(fwdSpeed) / 3f + 0.35f, 0f, 1.2f) * Mathf.Sign(fwdSpeed + 0.01f);
var av = Body.angularVelocity;
float spin = Vector3.Dot(av, up);
Body.angularVelocity = av + up * (Mathf.MoveTowards(spin, _steer * turnRate, dt * 8f) - spin);
// lean into turns, nose up when accelerating
var lean = up + transform.right * (_steer * fwdSpeed * 0.012f) - fwd * (throttle * 0.04f);
var tq = Vector3.Cross(transform.up, lean.normalized) * 18f - Body.angularVelocity * 2.5f;
Body.AddTorque(Vector3.ProjectOnPlane(tq, up) * Body.mass, ForceMode.Force);
}
if ((driving || auto) && Throttle.Value != throttle) Throttle.Value = throttle;
// mow under the cutter: what the header sweeps goes in the hopper
bool mowing = false;
if (onGround && Def.width > 0f)
{
var ip = intake ? intake.position : transform.position + fwd * length * 0.5f;
bool overMeadow = Planet.Altitude(ip) < 1.2f && !(Ground.Instance && Ground.Instance.RockAt(ip));
bool onDeck = Ts && Ts.OnDeck(ip);
if (overMeadow && !onDeck && Tank.Value < Capacity && (driving || auto))
{
mowing = true;
float kg = MowMap.Cut(_hasCut ? _lastCut : ip, ip, CutWidth, blade: true) * GameDefs.GrassDensity;
Tank.Value = Mathf.Min(Capacity, Tank.Value + kg);
if (Tank.Value >= Capacity - 0.01f && driving) { Sfx.Play("tank_full", 0.8f); Assistant.Say("asst_hopper"); Hud.Toast(Loc.F("{0} hopper full: unload at the base yard, a garage pad or an Unload Bay (follow the UNLOAD markers)", Def.name), Hud.ToastKind.Warn); }
_lastCut = ip;
}
_hasCut = mowing;
}
if (Slurping.Value != mowing) Slurping.Value = mowing;
// unload: in the yard at the base it's paid as it comes off, on a garage's pad or an unload bay it fills the bin
var pad = Tank.Value > 0.1f ? SiloPiece.PadUnder(transform.position) : null;
if (Def.bales && (driving || auto)) Bale(dt);
Unloading = Tank.Value > 0.1f && (pad || NearDock());
if (Tank.Value > 0.1f && (pad || NearDock()) && Ts)
{
float give = Mathf.Min(Tank.Value, GameDefs.DockRate(Level(TuneId.Release)) * (Ts.Has(PerkId.ExpressDepot) ? 2f : 1f) * dt);
Tank.Value -= give;
_unloadCarry += give;
if (_unloadCarry > 40f || Tank.Value <= 0.1f)
{
if (pad) pad.TakeRpc(_unloadCarry);
else Ts.DepositRpc(_unloadCarry, (byte)CargoKind.Grass, transform.position);
_unloadCarry = 0f;
}
}
}
float _baleT;
/// <summary>The chute is feeding a belt right now, for the HUD.</summary>
public bool Baling { get; private set; }
/// <summary>On a pad or in the yard with something in the hopper.</summary>
public bool Unloading { get; private set; }
public Vector3 ChuteAt => chute ? chute.position : transform.position + transform.right * (length * 0.35f + 1.2f) - transform.forward * length * 0.3f + transform.up * 0.6f;
/// <summary>
/// The baler: beside the start of a belt, its chute ties the hopper into 1 kg bundles and puts them on the belt, five a second,
/// as long as the belt has room. The driver's machine decides; the server makes the bundles.
/// </summary>
void Bale(float dt)
{
Baling = false;
if (Tank.Value < 1f) return;
if (!BeltNet.Nearest(ChuteAt, true, 3.2f, null, out var piece, out _, out _)) return;
var belt = piece.GetComponentInChildren<Conveyor>();
if (!belt || !belt.HasRoom) return;
Baling = true;
_baleT += dt;
if (_baleT < 0.2f) return;
_baleT = 0f;
Tank.Value -= 1f;
BaleRpc(ChuteAt);
}
[Rpc(SendTo.Server)]
void BaleRpc(Vector3 at)
{
if (!BeltNet.Nearest(at, true, 3.4f, null, out var piece, out int index, out var port)) { Ts?.DepositRpc(1f, (byte)CargoKind.Grass, at); return; }
var belt = piece.GetComponentInChildren<Conveyor>();
var made = Spawner.Instance.SpawnCargo(CargoKind.Grass, port.at + piece.transform.up * 0.3f, Quaternion.LookRotation(port.dir, piece.transform.up), Vector3.zero);
if (made && belt) belt.ServerAcceptPort(made, index);
}
Vector3 _lastCut, _seenAt;
bool _hasCut, _seenCut;
public bool NearDock()
{
if (!s_dock) { var d = GameObject.Find("DockZone"); s_dock = d ? d.transform : null; }
if (!s_dock) return false;
var p = s_dock.InverseTransformPoint(transform.position);
return Mathf.Abs(p.x) < 7f && Mathf.Abs(p.z) < 6f && Mathf.Abs(p.y) < 4f;
}
// ───────────────────────── visuals (everyone) ─────────────────────────
static Vector3 Axis(int a) => a == 0 ? Vector3.right : a == 1 ? Vector3.up : Vector3.forward;
/// <summary>Wings in while it's in the shed door, out again on the pad.</summary>
void Fold()
{
if (fold == null || fold.Length == 0) return;
if (_foldRest == null)
{
_foldRest = new Vector3[fold.Length];
for (int i = 0; i < fold.Length; i++) _foldRest[i] = fold[i] ? fold[i].localScale : Vector3.one;
}
float want = Folded.Value ? 1f : 0f;
if (Mathf.Approximately(_folded, want)) return;
_folded = Mathf.MoveTowards(_folded, want, Time.deltaTime / 1.1f);
float e = _folded * _folded * (3f - 2f * _folded);
for (int i = 0; i < fold.Length; i++)
if (fold[i]) fold[i].localScale = Vector3.Scale(_foldRest[i], new Vector3(Mathf.Lerp(1f, 0.32f, e), 1f, 1f));
}
void Visuals()
{
float thr = Mathf.Abs(Throttle.Value);
float speed = Body ? Vector3.ProjectOnPlane(Body.linearVelocity, Planet.Up(transform.position)).magnitude : 0f;
if (_engine)
{
_engine.volume = Mathf.MoveTowards(_engine.volume, HasDriver ? (0.25f + thr * 0.35f) * Sfx.SfxVolume : 0f, Time.deltaTime * 0.8f);
_engine.pitch = Mathf.Lerp(0.8f, 1.7f, Mathf.Clamp01(speed / 15f));
}
bool slurp = Slurping.Value;
if (_suck) _suck.volume = Mathf.MoveTowards(_suck.volume, slurp ? 0.35f * Sfx.SfxVolume : 0f, Time.deltaTime * 2f);
if (fill)
{
var s = fill.localScale;
fill.localScale = new Vector3(s.x, s.y, Mathf.Max(0.001f, Mathf.Lerp(s.z, Tank.Value / Mathf.Max(1f, Capacity), Time.deltaTime * 4f)));
}
if (bars) bars.localRotation = BaseRot.Of(bars) * Quaternion.Euler(0f, 0f, -_steer * 25f);
if (arm)
{
_armAngle = Mathf.Lerp(_armAngle, slurp ? Mathf.Sin(Time.time * 0.8f) * 25f : 0f, Time.deltaTime * 2f);
arm.localRotation = BaseRot.Of(arm) * Quaternion.Euler(0f, 0f, _armAngle);
}
_fanSpin += Time.deltaTime * (HasDriver ? 600f + thr * 900f : 80f);
if (fanL) fanL.localRotation = BaseRot.Of(fanL) * Quaternion.Euler(0f, _fanSpin, 0f);
if (fanR) fanR.localRotation = BaseRot.Of(fanR) * Quaternion.Euler(0f, -_fanSpin, 0f);
if (reel)
{
if (_reelAxis < 0) _reelAxis = BaseRot.LocalAxisFor(reel, transform.right);
reel.localRotation = BaseRot.Of(reel) * Quaternion.Euler(Axis(_reelAxis) * (Time.time * (slurp ? 260f : HasDriver ? 90f : 0f)));
}
if (wheels != null && wheels.Length > 0)
{
float fwdSpeed = Body ? Vector3.Dot(Body.linearVelocity, transform.forward) : 0f;
_wheelSpin += fwdSpeed * Time.deltaTime / 0.32f * Mathf.Rad2Deg;
if (_wheelAxis == null || _wheelAxis.Length != wheels.Length)
{
_wheelAxis = new int[wheels.Length];
_wheelFront = new bool[wheels.Length];
_wheelWay = new float[wheels.Length];
_wheelRest = new Vector3[wheels.Length];
_wheelDrop = new float[wheels.Length];
WheelRadius = new float[wheels.Length];
for (int i = 0; i < wheels.Length; i++)
{
if (!wheels[i]) continue;
_wheelRest[i] = wheels[i].localPosition;
WheelRadius[i] = TyreRadius(wheels[i]);
_wheelAxis[i] = BaseRot.LocalAxisFor(wheels[i], transform.right);
// some models were turned around when they came in, and their axles with them
_wheelWay[i] = Vector3.Dot(wheels[i].TransformDirection(Axis(_wheelAxis[i])), transform.right) < 0f ? -1f : 1f;
// Wheel_FL, or SM_Veh_Tractor_Wheel_fl from the pack
var n = wheels[i].name;
_wheelFront[i] = char.ToUpperInvariant(n[n.IndexOf("Wheel_", System.StringComparison.Ordinal) + 6]) == 'F';
}
}
for (int i = 0; i < wheels.Length; i++)
{
var w = wheels[i];
if (!w) continue;
var spin = Quaternion.Euler(Axis(_wheelAxis[i]) * (_wheelSpin * _wheelWay[i]));
// front wheels steer
var steer = _wheelFront[i] ? Quaternion.AngleAxis(_steer * 22f, w.parent ? w.parent.InverseTransformDirection(transform.up) : Vector3.up) : Quaternion.identity;
w.localRotation = steer * BaseRot.Of(w) * spin;
Settle(i);
}
}
if (slurp && intake)
{
var ip = intake.position;
var surf = Planet.Surface(ip);
var up = Planet.Up(ip);
// someone else's machine: mow the same strip here
if (!IsOwner)
{
MowMap.Cut(_seenCut ? _seenAt : ip, ip, CutWidth, blade: true);
_seenAt = ip;
_seenCut = true;
}
Meadow.Vortex(surf, 1f, Def.width * 0.7f);
_sprayT -= Time.deltaTime;
if (_sprayT <= 0f) { _sprayT = 0.04f; Fx.Droplets(surf + up * 0.3f, up - transform.forward * 0.6f + transform.right * 0.4f, 3); }
}
else _seenCut = false;
Tow();
Life(speed, thr);
if (speed > 2f)
{
_wakeT -= Time.deltaTime;
if (_wakeT <= 0f)
{
_wakeT = Mathf.Lerp(0.12f, 0.03f, speed / 15f);
var wp = wake ? wake.position : transform.position - transform.forward * length * 0.5f;
Fx.Wake(Planet.Surface(wp) + Planet.Up(wp) * 0.05f, -transform.forward, Mathf.Clamp01(speed / 12f));
}
}
}
/// <summary>
/// A wheel's travel: down onto the ground under it, or up out of it, along the machine's own up. The body rides on
/// four springs at its corners, not on the tyres, so without this a tyre of any other size hangs in the air or sinks.
/// </summary>
void Settle(int i)
{
var w = wheels[i];
if (!w.parent) return;
var up = transform.up;
var rest = w.parent.TransformPoint(_wheelRest[i]);
float clearance = Planet.Altitude(rest) / Mathf.Max(0.5f, Vector3.Dot(up, Planet.Up(rest)));
int groundMask = (1 << Layers.Default) | (1 << Layers.Build);
if (Physics.Raycast(rest + up * 0.6f, -up, out var hit, 0.6f + WheelRadius[i] + MaxDrop + 0.2f, groundMask, QueryTriggerInteraction.Ignore)
&& !hit.transform.IsChildOf(transform))
clearance = Mathf.Min(clearance, hit.distance - 0.6f);
float want = Mathf.Clamp(clearance - WheelRadius[i], -0.2f, MaxDrop);
_wheelDrop[i] = Mathf.Lerp(_wheelDrop[i], want, 1f - Mathf.Exp(-25f * Time.deltaTime));
w.position = rest - up * _wheelDrop[i];
}
const float MaxDrop = 0.4f;
public static float TyreRadius(Transform w)
{
var mf = w.GetComponentInChildren<MeshFilter>();
if (!mf || !mf.sharedMesh) return 0.4f;
var e = Vector3.Scale(mf.sharedMesh.bounds.extents, mf.transform.lossyScale);
e = new Vector3(Mathf.Abs(e.x), Mathf.Abs(e.y), Mathf.Abs(e.z));
// a tyre is a radius across two ways and half its width the third
return Mathf.Max(0.15f, Mathf.Max(e.x, Mathf.Max(e.y, e.z)));
}
// ───────── the towed part ─────────
Vector3 _axle;
float _towLen = -1f;
Quaternion _hitchRest;
/// <summary>
/// A trailer is dragged by its pin: its axle follows the hitch the way a real one does, so it swings out on a turn,
/// straightens up on the straight and folds toward a jack-knife backing up (stopped short of hitting the cab).
/// </summary>
void Tow()
{
if (!hitch) return;
var up = transform.up;
var h = hitch.position;
if (_towLen < 0f)
{
_hitchRest = hitch.localRotation;
Vector3 sum = Vector3.zero;
int n = 0;
if (wheels != null) foreach (var w in wheels) if (w && w.IsChildOf(hitch)) { sum += w.position; n++; }
var axle = n > 0 ? sum / n : h - transform.forward * 3f;
_towLen = Mathf.Max(0.5f, Vector3.ProjectOnPlane(axle - h, up).magnitude);
_axle = h - transform.forward * _towLen;
}
var d = Vector3.ProjectOnPlane(_axle - h, up);
// put somewhere new (a garage, the yard): it comes straight
if (d.sqrMagnitude < 1e-4f || (_axle - h).sqrMagnitude > _towLen * _towLen * 4f) d = -transform.forward;
float yaw = Mathf.Clamp(Vector3.SignedAngle(-transform.forward, d, up), -78f, 78f);
var back = Quaternion.AngleAxis(yaw, up) * -transform.forward;
_axle = h + back * _towLen;
var parent = hitch.parent ? hitch.parent : transform;
hitch.localRotation = Quaternion.AngleAxis(yaw, parent.InverseTransformDirection(up).normalized) * _hitchRest;
}
// ───────── a machine that looks alive ─────────
Vector3 _exhaustLocal;
bool _exhaustFound;
float _exT, _dustT, _lastThr, _pitchLean, _rollLean, _lastSpeed;
Quaternion _shellRest;
bool _shellSet;
/// <summary>
/// Smoke from the stack (a black cough when the throttle goes down hard), dust and clippings kicked up behind the
/// wheels, and the body settling back on its springs when it pulls away and leaning out on a turn.
/// </summary>
void Life(float speed, float thr)
{
float dt = Mathf.Max(1e-4f, Time.deltaTime);
var up = Planet.Up(transform.position);
if (!_exhaustFound)
{
_exhaustFound = true;
// the top of the bonnet just ahead of the cab, on the right: where the pack's stacks are
var b = new Bounds();
bool any = false;
foreach (var r in GetComponentsInChildren<MeshRenderer>(true))
{
if (hitch && r.transform.IsChildOf(hitch)) continue;
var c = transform.InverseTransformPoint(r.bounds.center);
if (!any) { b = new Bounds(c, Vector3.zero); any = true; }
b.Encapsulate(transform.InverseTransformPoint(r.bounds.min));
b.Encapsulate(transform.InverseTransformPoint(r.bounds.max));
}
_exhaustLocal = any ? new Vector3(b.extents.x * 0.32f, b.max.y * 0.9f, b.center.z + b.extents.z * 0.35f) : new Vector3(0.3f, 2f, 0.6f);
}
if (HasDriver)
{
bool push = thr - _lastThr > 0.45f;
_exT -= dt;
if (_exT <= 0f || push)
{
_exT = Mathf.Lerp(0.22f, 0.06f, thr);
Fx.Exhaust(transform.TransformPoint(_exhaustLocal), up, push ? 1.6f : 0.35f + thr * 0.6f);
}
}
_lastThr = Mathf.MoveTowards(_lastThr, thr, dt * 2.5f);
if (speed > 1.6f && wheels != null && wheels.Length > 0)
{
_dustT -= dt;
if (_dustT <= 0f)
{
_dustT = Mathf.Lerp(0.14f, 0.035f, Mathf.Clamp01(speed / 14f));
var w = wheels[Random.Range(0, wheels.Length)];
if (w) Fx.Kick(Planet.Surface(w.position), -transform.forward, Mathf.Clamp01(speed / 12f));
}
}
if (shell)
{
if (!_shellSet) { _shellSet = true; _shellRest = shell.localRotation; }
float accel = (speed - _lastSpeed) / dt;
_lastSpeed = speed;
float yawRate = Body ? Vector3.Dot(Body.angularVelocity, up) : 0f;
_pitchLean = Mathf.Lerp(_pitchLean, Mathf.Clamp(-accel * 0.35f, -2.2f, 2.2f), dt * 4f);
_rollLean = Mathf.Lerp(_rollLean, Mathf.Clamp(yawRate * speed * 0.6f, -2.5f, 2.5f), dt * 4f);
// a little engine shiver at idle
float shiver = HasDriver ? Mathf.Sin(Time.time * 47f) * 0.12f * (1f - Mathf.Clamp01(speed / 4f)) : 0f;
shell.localRotation = Quaternion.Euler(_pitchLean + shiver, 0f, _rollLean) * _shellRest;
}
}
}
}