Files
grass-cutters/Assets/Scripts/Player/PlayerAgent.cs
NiemandKG 88c1ee9202 Base fixes: climb over the railing, hay on the deck, no yard logs, console back, logo T
- Climbing up from the meadow rises straight up the side until the feet clear the
  railing, goes over it and drops onto the deck, instead of an arc through the fence.
- Props stand their lowest point on the floor (the hay bale was half under the deck).
- The timber bay lines on the unloading yard are gone.
- SM_Terminal: the chalkboard's back stands proud of the frame bars, no more
  flickering where their back faces shared a plane.
- Logo: the scythe standing in for the first T of CUTTERS is now a plain T
  (Tools/ui/logo_t.py copies the second T); menu logo, Steam capsules and the
  demo's capsules rebuilt from it.
- -demofix: close shots of those spots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:08:13 +06:00

860 lines
40 KiB
C#

using System.Collections.Generic;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// First-person GreenHaul crew member: walking (slowed by tall grass), climbing onto the deck and vaulting off it,
/// jetpack dash, personal tools and gear, riding vehicles, interaction ray and identity (name / Steam ID / vest colour).
/// </summary>
[RequireComponent(typeof(CrewBody))]
public class PlayerAgent : NetworkBehaviour, ICrewPose
{
public static readonly List<PlayerAgent> All = new List<PlayerAgent>();
public static PlayerAgent Local { get; private set; }
public static readonly Color[] Palette =
{
new Color(1f, 0.48f, 0.1f), // safety orange
new Color(0.09f, 0.7f, 0.77f), // teal
new Color(1f, 0.36f, 0.6f), // bubblegum
new Color(0.45f, 0.85f, 0.25f),// lime
new Color(0.55f, 0.4f, 1f), // violet
new Color(0.95f, 0.22f, 0.22f),// red
new Color(0.22f, 0.5f, 1f), // blue
new Color(0.96f, 0.96f, 0.94f),// white
};
/// <summary>The key of this player's things in the host's save, as the host settled it: everyone needs it, the garage looks up "my machine" by it.</summary>
public readonly NetworkVariable<FixedString64Bytes> SaveKey = new NetworkVariable<FixedString64Bytes>("");
public readonly NetworkVariable<FixedString64Bytes> NetName = new NetworkVariable<FixedString64Bytes>("", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<ulong> SteamId = new NetworkVariable<ulong>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<int> ColorIndex = new NetworkVariable<int>();
/// <summary>Which of the <see cref="Roster"/> this player goes as.</summary>
public readonly NetworkVariable<byte> Character = new NetworkVariable<byte>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<float> Pitch = new NetworkVariable<float>(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<byte> ToolNet = new NetworkVariable<byte>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<bool> Driving = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<bool> Swimming = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Phone in hand, for the others to see. What's on it stays private.</summary>
public readonly NetworkVariable<bool> PhoneOut = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<bool> Jetting = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Kilos in the container of the tool in hand.</summary>
public readonly NetworkVariable<float> Tank = new NetworkVariable<float>(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Cutting right now: where the blade is, w = strip width (0 = not cutting). Remote clients mow the same strip.</summary>
public readonly NetworkVariable<Vector4> CutAt = new NetworkVariable<Vector4>(Vector4.zero, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Bit per <see cref="ToolId"/> / <see cref="GearId"/> this player has: tools are personal, upgrades shared.</summary>
public readonly NetworkVariable<ushort> Owned = new NetworkVariable<ushort>();
public readonly NetworkVariable<byte> BeltSlots = new NetworkVariable<byte>(1);
[Header("Movement")]
public float walkSpeed = 4.4f;
public float sprintSpeed = 7.2f;
public float swimSpeed = 2.7f;
public float jumpVelocity = 6.9f;
public float gravity = -19f;
public float eyeHeight = 1.12f;
public Transform head;
public PlayerTools Tools { get; private set; }
public PlayerGrab Grab { get; private set; }
public CrewAvatar Avatar { get; private set; }
public CrewBody Body { get; private set; }
public string DisplayName => string.IsNullOrEmpty(NetName.Value.ToString()) ? "Crew " + OwnerClientId : NetName.Value.ToString();
public Color Tint => Palette[Mathf.Abs(ColorIndex.Value) % Palette.Length];
public Vector3 Velocity => _vel;
public bool Grounded { get; private set; }
public bool Sprinting { get; private set; }
public bool IsSwimming => _swimming;
/// <summary>Standing down in the meadow (not on the deck): tall grass slows you, In The Weeds speeds up mowing.</summary>
public bool InGrass { get; private set; }
public bool Owns(ToolId t) => t != ToolId.None && (Owned.Value >> (int)t & 1) != 0;
public bool HasGear(GearId g) => (Owned.Value >> (int)g & 1) != 0;
/// <summary>Gravity boots on: Earth's pull instead of Herbaria's.</summary>
public bool BootsOn { get; set; }
/// <summary>Key of this player's tools in the host's save.</summary>
public string SaveId => SaveKey.Value.IsEmpty ? null : SaveKey.Value.ToString();
public bool ClaimedSave => SaveId != null;
public Vehicle Vehicle => _vehicle;
// interaction
public RaycastHit AimHit { get; private set; }
/// <summary>The built piece in the crosshair, if it has anything to set (not the company's).</summary>
public BuildPiece AimPiece
{
get
{
if (!HasAim || !AimHit.collider) return null;
var p = AimHit.collider.GetComponentInParent<BuildPiece>();
return p && !p.Def.company && (p.Upgrades != UpgradeKind.None || p.GetComponentInChildren<IJunction>() != null) ? p : null;
}
}
public bool HasAim { get; private set; }
public IInteractable AimInteractable { get; private set; }
public Grabbable AimGrabbable { get; private set; }
public const float Reach = 2.8f;
/// <summary>Where we stand and face: its up is always the planet's up here, turned by the mouse.</summary>
Quaternion _frame = Quaternion.identity;
Quaternion _heading = Quaternion.identity;
Unity.Netcode.Components.NetworkTransform _net;
bool _settled;
float _pitch;
Vector3 _vel;
float _launchUntil;
/// <summary>Something throws you (a twister): you fly loose for a moment and steering barely counts.</summary>
public void Fling(Vector3 vel)
{
if (!IsOwner) return;
_vel = vel;
_launchUntil = Time.time + 1.4f;
CameraFx.Shake(0.45f);
}
bool _swimming;
float _climbT = -1f;
Vector3 _climbFrom, _climbTo;
/// <summary>Climbing up onto the deck goes over its railing (1.05 m), not through it.</summary>
bool _climbOver;
const float RailClear = 1.2f;
float _jumpTapAt = -9f, _dashAt = -9f;
Vehicle _vehicle;
/// <summary>The train whose cab this player rides in, and the lever as last sent.</summary>
Train _train;
sbyte _lever;
public Train RidingTrain => _train;
/// <summary>In a seat of some kind: a machine's, or a train's cab.</summary>
bool Seated => _vehicle || _train;
public bool Flying { get; private set; }
public float CheatSpeed = 1f;
TeamState Ts => TeamState.Instance;
public void SetFlying(bool on)
{
if (!IsOwner || Seated || Flying == on) return;
Flying = on;
Body.enabled = !on;
_vel = Vector3.zero;
}
void Fly()
{
var input = Ctl.Move;
float up = (Ctl.JumpHeld ? 1f : 0f) - (Ctl.DownHeld ? 1f : 0f);
var dir = head.forward * input.y + transform.right * input.x + transform.up * up;
float speed = 11f * CheatSpeed * (Ctl.Sprint ? 2.5f : 1f);
_vel = Vector3.MoveTowards(_vel, Vector3.ClampMagnitude(dir, 1f) * speed, 60f * Time.deltaTime);
transform.position += _vel * Time.deltaTime;
Grounded = false;
CameraFx.FovTarget(_vel.magnitude > 12f ? 7f : 0f);
}
float _coyote, _jumpBuffer, _bobPhase, _stepAcc, _landDip, _airTime, _lean;
bool _wasGrounded = true;
void Awake()
{
Body = GetComponent<CrewBody>();
_net = GetComponent<Unity.Netcode.Components.NetworkTransform>();
Body.Bumped += Bump;
Tools = GetComponent<PlayerTools>();
Grab = GetComponent<PlayerGrab>();
Avatar = GetComponentInChildren<CrewAvatar>(true);
if (!head) head = transform.Find("Head");
}
bool ICrewPose.IsSwimming => Swimming.Value;
bool ICrewPose.IsDriving => Driving.Value;
bool ICrewPose.InCab => Driving.Value && Vehicle.All.Exists(v => v.Driver.Value == OwnerClientId && v.Def.seatDrop > 0f);
bool ICrewPose.HasPhoneOut => PhoneOut.Value;
byte ICrewPose.Held => ToolNet.Value;
float ICrewPose.LookPitch => Pitch.Value;
float ICrewPose.TankKilos => Tank.Value;
Vector4 ICrewPose.CutLine => CutAt.Value;
Color ICrewPose.Colour => Tint;
public override void OnNetworkSpawn()
{
All.Add(this);
if (IsServer) ColorIndex.Value = PickColor();
if (IsOwner)
{
Local = this;
NetName.Value = new FixedString64Bytes(Truncate(SteamManager.MyName, 24));
SteamId.Value = SteamManager.Initialized ? SteamManager.MySteamId.m_SteamID : 0;
Character.Value = (byte)GameSettings.Character;
gameObject.layer = Layers.LocalPlayer;
Teleport(SpawnPoint());
AttachCamera();
Ctl.SetCursor(true);
Hud.OnLocalPlayerSpawned(this);
ClaimSaveRpc(SteamManager.Initialized ? SteamManager.MySteamId.m_SteamID.ToString() : "local");
}
if (Avatar)
{
Avatar.Setup(this, IsOwner, Character.Value);
Character.OnValueChanged += (_, who) => Avatar.Dress(who);
ColorIndex.OnValueChanged += (_, __) => Avatar.ApplyTint();
}
}
public override void OnNetworkDespawn()
{
All.Remove(this);
if (IsOwner && Local == this)
{
Local = null;
Phone.I?.Unbind();
MenuCamera.Reclaim();
}
if (IsServer)
foreach (var v in Vehicle.All) if (v && v.Driver.Value == OwnerClientId) v.ServerEject();
}
[Rpc(SendTo.Server)]
void ClaimSaveRpc(FixedString64Bytes id)
{
string key = id.ToString();
if (Ts && OwnerClientId != NetworkManager.ServerClientId && Ts.Banned(key))
{
NetworkManager.DisconnectClient(OwnerClientId, Loc.Pack("You are banned from this game"));
return;
}
// two players under one key (no Steam, or one account on two copies) would share one fleet and one set of
// tools: the second one gets a key of its own
if (All.Exists(p => p && p != this && p.SaveId == key)) key += "#" + OwnerClientId;
SaveKey.Value = new FixedString64Bytes(key);
if (Ts)
{
Ts.ServerRestoreCrew(this);
Ts.ServerSendMow(OwnerClientId);
}
}
[Rpc(SendTo.Server)]
public void ReportToolsRpc(float[] bins, int[] belt, int current)
{
if (Ts) Ts.ServerStoreTools(this, bins, belt, current);
}
/// <summary>The travel terminal sends you here.</summary>
[Rpc(SendTo.Owner)]
public void ArriveRpc(Vector3 at)
{
Teleport(at);
Sfx.Play("ui_open", 0.8f, 0.6f);
}
/// <summary>This player bought a treat: everyone else sees the machine do its show, and smoke or bubbles off them for a while.</summary>
[Rpc(SendTo.NotMe)]
public void TreatRpc(byte kind, Vector3 machine, Vector3 from)
{
VendingMachine.Nearest(machine)?.Play(false, from);
if (kind == (byte)TreatId.Beer) _remoteBeer = Time.time + Treats.Seconds + 3f;
else _remoteCigar = Time.time + Treats.Seconds + 4f;
}
float _remoteBeer = -1f, _remoteCigar = -1f, _remotePuff;
/// <summary>Someone else on a treat: a puff of smoke from the cigar smoker now and then, bubbles off the beer drinker.</summary>
void RemoteTreats()
{
if (IsOwner) return;
bool beer = Time.time < _remoteBeer, cigar = Time.time < _remoteCigar;
if (!beer && !cigar) return;
_remotePuff -= Time.deltaTime;
if (_remotePuff > 0f) return;
_remotePuff = Random.Range(2.5f, 4.5f);
var head = transform.position + transform.up * 1.7f + transform.forward * 0.25f;
if (cigar) Fx.Exhale(head, transform.forward, 0.6f);
if (beer) Fx.Bubbles(head, 6);
}
[Rpc(SendTo.Owner)]
public void RestoreToolsRpc(int owned, float[] bins, int[] belt, int current) => Tools.Restore(owned, bins, belt, current);
public override void OnDestroy()
{
All.Remove(this);
if (Local == this) Local = null;
base.OnDestroy();
}
static string Truncate(string s, int n) => string.IsNullOrEmpty(s) ? "Crew" : (s.Length <= n ? s : s.Substring(0, n));
int PickColor()
{
var used = new HashSet<int>();
foreach (var p in All) if (p != this) used.Add(p.ColorIndex.Value);
for (int i = 0; i < Palette.Length; i++) if (!used.Contains(i)) return i;
return (int)(OwnerClientId % (ulong)Palette.Length);
}
Vector3 SpawnPoint()
{
var sp = GameObject.Find("SpawnPoints");
if (sp && sp.transform.childCount > 0)
{
var t = sp.transform.GetChild((int)(OwnerClientId % (ulong)sp.transform.childCount));
_frame = Quaternion.Euler(0f, t.eulerAngles.y, 0f);
return t.position;
}
return new Vector3(0, 0.1f, -3f);
}
public void Teleport(Vector3 pos)
{
Body.enabled = false;
transform.position = pos;
KeepUpright(true);
transform.rotation = _frame;
// everyone else sees a jump too, not a glide straight through the planet
if (_net && _net.IsSpawned && _settled) _net.Teleport(pos, _frame, transform.localScale);
Body.enabled = !Flying && !Seated;
_vel = Vector3.zero;
_climbT = -1f;
}
public void LookAt(Vector3 target)
{
var up = Planet.Up(transform.position);
var d = target - (transform.position + up * eyeHeight);
var flat = Vector3.ProjectOnPlane(d, up);
if (flat.sqrMagnitude > 1e-6f) _frame = Quaternion.LookRotation(flat, up);
_pitch = -Mathf.Atan2(Vector3.Dot(d, up), flat.magnitude) * Mathf.Rad2Deg;
transform.rotation = _frame;
}
/// <summary>Which way is up for the crewman now (eased, so stepping on and off the deck doesn't jolt the view).</summary>
Vector3 _stand;
/// <summary>
/// Turn the frame just enough to bring its up onto the planet's up here: heading carries over the ball. On the deck
/// it is the deck's up instead: the base is laid flat on the pole, so on a small planet its far edge leans well off
/// the planet's up, and standing to the planet there looked like a tilted head among upright walls.
/// </summary>
void KeepUpright(bool snap = false)
{
var want = Planet.Up(transform.position);
var ts = Ts;
if (ts && !Flying && !_vehicle && ts.OnDeck(transform.position)) want = Vector3.up;
_stand = snap || _stand == Vector3.zero ? want : Vector3.Slerp(_stand, want, 1f - Mathf.Exp(-6f * Time.deltaTime)).normalized;
_frame = Quaternion.FromToRotation(_frame * Vector3.up, _stand) * _frame;
}
/// <summary>Third person in a machine: the camera hangs on this boom behind it. On foot and in the seat the boom sits on the eyes.</summary>
Transform _boom;
/// <summary>Remembered between rides and runs: whoever likes the chase view gets it every time.</summary>
public static bool ChaseView
{
get => PlayerPrefs.GetInt("chase_view", 1) == 1;
set => PlayerPrefs.SetInt("chase_view", value ? 1 : 0);
}
static float _chaseDist = -1f;
float _chaseShown;
bool _bodyShown;
public bool InChaseView => _vehicle && ChaseView;
void AttachCamera()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
MenuCamera.Release();
if (!_boom)
{
_boom = new GameObject("CameraBoom").transform;
_boom.SetParent(head, false);
}
cam.transform.SetParent(_boom, false);
cam.transform.localPosition = Vector3.zero;
cam.transform.localRotation = Quaternion.identity;
}
// ───────────────────────── update ─────────────────────────
void Update()
{
if (!IsSpawned) return;
if (!IsOwner)
{
if (head) head.localRotation = Quaternion.Euler(Pitch.Value, 0, 0);
RemoteTreats();
return;
}
_settled = true;
if (Ctl.KeyDown(UnityEngine.InputSystem.Key.F9) && IsServer && Ts) Ts.ServerSetMoney(Ts.Money.Value + 500);
if (Ctl.BootsPressed && HasGear(GearId.Boots))
{
BootsOn = !BootsOn;
Sfx.Play("land", 0.5f, BootsOn ? 0.8f : 1.2f);
Hud.Toast(BootsOn ? Loc.T("Gravity boots on: Earth's pull") : Loc.T("Gravity boots off"), Hud.ToastKind.Info);
}
Look();
if (_vehicle) UpdateRiding();
else if (_train) RideTrain();
else if (Flying) Fly();
else if (_climbT >= 0f) Climb();
else Move();
UpdateAim();
if (Ctl.InteractPressed) DoInteract();
// T on anything built opens its upgrades and switches (the hammer keeps T for moving pieces)
if (Ctl.MovePressed && !Seated && AimPiece && !(PlayerBuild.Local && PlayerBuild.Local.Active)) UIRoot.I?.OpenPiece(AimPiece);
// never lost under the soil
if (!Flying && !Seated && Planet.Altitude(transform.position) < -3f) Teleport(Planet.Surface(transform.position) + Planet.Up(transform.position) * 0.1f);
if (Swimming.Value != _swimming) Swimming.Value = _swimming;
var cp = Tools.CutPoint;
var cut = Tools.IsCutting && Ts ? new Vector4(cp.x, cp.y, cp.z, Ts.ToolWidth(Tools.Current)) : Vector4.zero;
if ((cut - CutAt.Value).sqrMagnitude > 0.04f || (cut.w > 0f) != (CutAt.Value.w > 0f)) CutAt.Value = cut;
}
void Look()
{
var l = Ctl.Look;
KeepUpright();
var up = _frame * Vector3.up;
_frame = Quaternion.AngleAxis(l.x, up) * _frame;
_pitch = Mathf.Clamp(_pitch - l.y, -85f, 85f);
if (!Seated) transform.rotation = _frame;
float flat = Vector3.ProjectOnPlane(_vel, up).magnitude;
float bob = (Grounded || _swimming) && !Seated && GameSettings.HeadBob ? Mathf.Sin(_bobPhase * 2f) * (_swimming ? 0.05f : 0.035f) * Mathf.Clamp01(flat / sprintSpeed + (_swimming ? 0.4f : 0f)) : 0f;
// the head leans into a sidestep: it follows the body's sideways speed and eases in and out, instead of snapping
// with the A / D key (which jerked the view on every press and release)
float side = Seated || Flying ? 0f : Mathf.Clamp(Vector3.Dot(_vel, _frame * Vector3.right) / walkSpeed, -1.3f, 1.3f);
_lean = Mathf.Lerp(_lean, -side * 1.2f, 1f - Mathf.Exp(-Time.deltaTime * 6f));
float roll = _lean;
if (_swimming) roll += Mathf.Sin(Time.time * 1.3f) * 2f;
_landDip = Mathf.Lerp(_landDip, 0f, Time.deltaTime * 8f);
head.localPosition = new Vector3(0, eyeHeight + bob - _landDip, 0);
if (Seated)
{
// look is relative to the vehicle heading
head.rotation = _frame * Quaternion.Euler(_pitch, 0f, 0f);
}
else head.localRotation = Quaternion.Euler(_pitch, 0, roll);
if (Mathf.Abs(Pitch.Value - _pitch) > 1.5f) Pitch.Value = _pitch;
}
void Move()
{
var input = Ctl.Move;
var ts = Ts;
var up = transform.up;
_swimming = false;
InGrass = Planet.Altitude(transform.position) < 0.6f && !(ts && ts.OnDeck(transform.position));
Sprinting = Ctl.Sprint && input.y > 0.1f && !Grab.Holding;
float speedMul = ts ? GameDefs.MoveMul(ts.Level(PerkId.ServoBoots), ts.Level(PerkId.FieldFrame)) : 1f;
if (Grab.Holding) speedMul *= 0.85f;
if (Tools.IsCutting) speedMul *= 0.8f;
// a Herb Cigar puts a spring in your step
speedMul *= Treats.MoveMul;
// wading through the meadow: uncut grass slows you down
if (InGrass) speedMul *= Mathf.Lerp(1f, 0.82f, MowMap.Yield(transform.position));
float speed = (Sprinting ? sprintSpeed : walkSpeed) * speedMul * CheatSpeed;
var wish = (transform.right * input.x + transform.forward * input.y) * speed;
Grounded = Body.isGrounded;
if (Grounded) _coyote = 0.12f; else _coyote -= Time.deltaTime;
if (Ctl.JumpPressed) _jumpBuffer = 0.14f; else _jumpBuffer -= Time.deltaTime;
// SPACE at the deck edge: climb up from the meadow, or vault over the railing down into it
if (Grounded && Ctl.JumpPressed && (InGrass ? TryClimb() : TryVault())) { _jumpBuffer = 0f; return; }
bool launched = Time.time < _launchUntil;
float accel = launched ? 2.5f : Grounded ? 55f : 14f;
float climb = Vector3.Dot(_vel, up);
var horiz = Vector3.MoveTowards(_vel - up * climb, wish, accel * Time.deltaTime);
if (Grounded && climb < 0f) climb = -2f;
if (_jumpBuffer > 0f && _coyote > 0f)
{
climb = (BootsOn ? jumpVelocity : GameDefs.LowJump) * (ts ? GameDefs.JumpMul(ts.Level(PerkId.SpringStep), ts.Level(PerkId.FieldFrame)) : 1f);
_jumpBuffer = 0f; _coyote = 0f;
Sfx.Play("jump", 0.6f);
Avatar?.Squash(0.15f);
}
// jetpack: double-tap SPACE in the air for a dash forward
if (Ctl.JumpPressed)
{
if (!Grounded && HasGear(GearId.Jetpack) && Time.time - _jumpTapAt < 0.35f && Time.time >= _dashAt)
{
_dashAt = Time.time + GameDefs.JetCooldown;
horiz = (wish.sqrMagnitude > 0.01f ? wish.normalized : transform.forward) * GameDefs.JetDash;
climb = Mathf.Max(climb, 3f);
_launchUntil = Time.time + 0.4f;
Fx.Droplets(transform.position + up * 0.5f - transform.forward * 0.35f, -up, 12);
Sfx.Play("throw_whoosh", 0.7f, 0.7f);
CameraFx.FovKick(5f);
Jetting.Value = true;
}
_jumpTapAt = Time.time;
}
if (Jetting.Value && Time.time >= _launchUntil) Jetting.Value = false;
climb += (BootsOn ? gravity : -GameDefs.LowGravity) * Time.deltaTime;
_vel = horiz + up * climb;
if (!Grounded) _airTime += Time.deltaTime;
Body.Move(_vel * Time.deltaTime);
bool nowGrounded = Body.isGrounded;
if (nowGrounded && !_wasGrounded && _airTime > 0.12f)
{
_launchUntil = 0f;
float landSpeed = -climb;
float hard = Mathf.InverseLerp(3f, 12f, landSpeed);
_landDip = 0.06f + hard * 0.14f;
Sfx.Play("land", 0.35f + hard * 0.5f, 1f - hard * 0.2f);
if (hard > 0.3f) { Fx.Dust(transform.position, 0.3f, 6); CameraFx.Shake(hard * 0.25f); }
Avatar?.Squash(0.1f + hard * 0.3f);
}
if (nowGrounded) _airTime = 0f;
_wasGrounded = nowGrounded;
float flat = horiz.magnitude;
if (nowGrounded && flat > 0.5f)
{
_bobPhase += Time.deltaTime * flat * 1.55f;
_stepAcc += flat * Time.deltaTime;
if (_stepAcc > (Sprinting ? 1.6f : 1.25f))
{
_stepAcc = 0f;
// 1 and 2 are grass, 3 and 4 are boards
bool boards = TeamState.Instance && TeamState.Instance.OnDeck(transform.position);
Sfx.Play("footstep_" + (boards ? Random.Range(3, 5) : Random.Range(1, 3)), Sprinting ? 0.35f : 0.22f, 1.1f, 0.1f);
}
}
CameraFx.FovTarget(Sprinting && flat > walkSpeed ? 7f : 0f);
}
/// <summary>From the meadow: is the deck (or a vehicle) edge right in front of us? Then climb up onto it.</summary>
bool TryClimb()
{
var fwd = transform.forward;
var up = transform.up;
var from = transform.position + up * 2.6f + fwd * 0.95f;
if (!Physics.Raycast(from, -up, out var hit, 2.4f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore)
|| Vector3.Dot(hit.normal, up) < 0.6f || Vector3.Dot(hit.point - transform.position, up) < 0.55f) return false;
_climbFrom = transform.position;
_climbTo = hit.point + up * 0.05f + fwd * 0.45f;
_climbT = 0f;
_climbOver = true;
Body.enabled = false;
Sfx.Play("splash_small", 0.5f, 1.3f);
Sfx.Play("jump", 0.5f, 0.85f);
Fx.Splash(transform.position, 0.4f);
return true;
}
/// <summary>On the deck, facing an open edge railing: vault over it down into the meadow.</summary>
bool TryVault()
{
var ts = Ts;
if (!ts || !ts.OnDeck(transform.position)) return false;
var fwd = transform.forward;
var up = transform.up;
if (!Physics.Raycast(transform.position + up * 0.5f, fwd, out var rail, 1.1f, 1 << Physics.IgnoreRaycastLayer, QueryTriggerInteraction.Ignore)) return false;
var beyond = rail.point + fwd * 1.3f;
if (ts.OnDeck(beyond)) return false;
var to = Planet.Surface(beyond);
if (Physics.Raycast(beyond + up * 3f, -up, out var land, 8f, (1 << Layers.Default) | (1 << Layers.Build), QueryTriggerInteraction.Ignore)) to = land.point;
_climbFrom = transform.position;
_climbTo = to + up * 0.05f;
_climbT = 0f;
_climbOver = false;
Body.enabled = false;
Sfx.Play("jump", 0.55f, 1f);
Avatar?.Squash(0.15f);
return true;
}
void Climb()
{
_climbT += Time.deltaTime / (_climbOver ? 0.7f : 0.55f);
float k = Mathf.Clamp01(_climbT);
if (_climbOver)
{
// up from the meadow: straight up the side until the feet clear the railing, over it, then down onto the deck
var up = transform.up;
float rise = Vector3.Dot(_climbTo - _climbFrom, up) + RailClear;
var top = _climbFrom + up * rise;
var over = _climbTo + up * RailClear;
if (k < 0.45f) transform.position = Vector3.Lerp(_climbFrom, top, Easing.Apply(Ease.OutQuad, k / 0.45f));
else if (k < 0.8f) transform.position = Vector3.Lerp(top, over, Easing.Apply(Ease.InOutQuad, (k - 0.45f) / 0.35f));
else transform.position = Vector3.Lerp(over, _climbTo, Easing.Apply(Ease.InQuad, (k - 0.8f) / 0.2f));
}
else
{
var mid = Vector3.Lerp(_climbFrom, _climbTo, 0.5f) + transform.up * 1.4f;
var a = Vector3.Lerp(_climbFrom, mid, k);
var b = Vector3.Lerp(mid, _climbTo, k);
transform.position = Vector3.Lerp(a, b, k);
}
if (k >= 1f)
{
_climbT = -1f;
Body.enabled = true;
_swimming = false;
_vel = Vector3.zero;
Avatar?.Squash(0.3f);
Fx.Droplets(transform.position + transform.up * 0.5f, transform.up, 10);
}
}
void Bump(RaycastHit hit, Vector3 dir)
{
var rb = hit.rigidbody;
if (!rb) return;
var g = rb.GetComponent<Grabbable>();
if (!g || g.IsHeld) return;
var up = transform.up;
g.Push((dir + up * 0.1f) * Mathf.Max(1.5f, Vector3.ProjectOnPlane(_vel, up).magnitude) * 0.6f);
}
// ───────────────────────── aim & interaction ─────────────────────────
void UpdateAim()
{
var cam = CameraFx.Cam;
AimInteractable = null;
AimGrabbable = null;
HasAim = false;
if (!cam || Seated) return;
var ray = new Ray(cam.transform.position, cam.transform.forward);
float tether = Ts ? Ts.Level(PerkId.BundleLine) * 1.5f : 0f;
if (Physics.Raycast(ray, out var hit, Reach + tether + (InGrass ? 0.6f : 0f), Layers.InteractMask, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<PlayerAgent>() == this) return;
var grab = hit.collider.GetComponentInParent<Grabbable>();
// only bundles come to you from beyond arm's length
if (hit.distance > Reach + (InGrass ? 0.6f : 0f) && !grab) return;
HasAim = true;
AimHit = hit;
AimInteractable = hit.collider.GetComponentInParent<IInteractable>();
AimGrabbable = grab;
}
}
void DoInteract()
{
if (_train) { _train.Leave(); return; }
if (_vehicle) { _vehicle.RequestExit(); return; }
if (Grab.Holding)
{
var bundle = Grab.Held ? Grab.Held.GetComponent<Cargo>() : null;
if (bundle && AimInteractable is Vehicle bed && bed.Def.bed > 0) bed.LoadRpc(bundle.NetworkObjectId);
else if (bundle && AimInteractable is ICargoSink && AimInteractable is NetworkBehaviour piece) bundle.HandInRpc(piece.NetworkObjectId);
else if (bundle && AimInteractable is Depot depot) bundle.HandInRpc(depot.GetComponent<BuildPiece>().NetworkObjectId);
else Grab.Drop();
return;
}
if (AimInteractable != null && (AimInteractable as Component)) { AimInteractable.Interact(); return; }
if (AimGrabbable && !AimGrabbable.IsHeld) Grab.TryGrab(AimGrabbable);
}
// ───────────────────────── vehicles ─────────────────────────
void LateUpdate()
{
if (!IsOwner || !IsSpawned) return;
if (!_vehicle)
{
// the machine went away under the driver (despawned or sold): back on foot where it was
if (Driving.Value)
{
_vehicle = null;
Driving.Value = false;
Body.enabled = !Flying;
}
foreach (var v in Vehicle.All)
if (v && v.LocalDriving) { EnterVehicle(v); break; }
}
else if (!_vehicle.LocalDriving) ExitVehicle();
if (_vehicle) FollowSeat();
// the train: the host says who is in its cab
if (!_train)
{
if (!_vehicle)
foreach (var t in Train.All)
if (t && t.IsSpawned && t.Rider.Value == OwnerClientId) { EnterTrain(t); break; }
}
else if (!_train.IsSpawned || _train.Rider.Value != OwnerClientId) ExitTrain();
if (_train) FollowCab();
Boom();
}
// ───────────────────────── the train's cab ─────────────────────────
void EnterTrain(Train t)
{
SetFlying(false);
_train = t;
_lever = 0;
Body.enabled = false;
_swimming = false;
_climbT = -1f;
Grab.Drop();
_heading = CabHeading(t);
_frame = _heading;
Sfx.Play("build_place", 0.5f, 1.3f);
Hud.Toast(Loc.T("In the cab: W forward · S back · E to get off"), Hud.ToastKind.Info);
}
void ExitTrain()
{
var t = _train;
_train = null;
_lever = 0;
var at = t ? t.StepOff : transform.position;
var up = Planet.Up(at);
var pos = Planet.Surface(at) + up * 0.1f;
if (Physics.Raycast(at + up * 2f, -up, out var hit, 6f, (1 << Layers.Default) | (1 << Layers.Build), QueryTriggerInteraction.Ignore)) pos = hit.point + up * 0.1f;
Teleport(pos);
}
/// <summary>The lever: W on up the line, S back toward home, neither to stop.</summary>
void RideTrain()
{
if (!_train) return;
var m = Ctl.Move;
sbyte lever = (sbyte)(m.y > 0.3f ? 1 : m.y < -0.3f ? -1 : 0);
if (lever != _lever)
{
_lever = lever;
_train.DriveRpc(lever);
}
CameraFx.FovTarget(lever != 0 ? 6f : 0f);
}
static Quaternion CabHeading(Train t)
{
var up = Planet.Up(t.CabFloor);
var f = Vector3.ProjectOnPlane(t.CabTurn * Vector3.forward, up);
return Quaternion.LookRotation(f.sqrMagnitude > 1e-6f ? f.normalized : Vector3.ProjectOnPlane(Vector3.forward, up).normalized, up);
}
void FollowCab()
{
transform.position = _train.CabFloor;
var heading = CabHeading(_train);
_frame = heading * Quaternion.Inverse(_heading) * _frame;
_heading = heading;
transform.rotation = heading;
}
/// <summary>
/// The chase view: the camera orbits the machine with the mouse, the wheel pulls it closer or further, and it never ends up
/// in the ground or behind a wall. Leaving the seat puts it back on the eyes.
/// </summary>
void Boom()
{
if (!_boom) return;
if (_vehicle && Ctl.ViewPressed)
{
ChaseView = !ChaseView;
Sfx.Play("ui_hover", 0.5f, ChaseView ? 0.9f : 1.2f);
Hud.Toast(ChaseView ? Loc.T("Chase view · wheel zooms · R back to the seat") : Loc.T("Driver's seat · R for the chase view"), Hud.ToastKind.Info);
}
bool chase = InChaseView;
if (Avatar && chase != _bodyShown) { _bodyShown = chase; Avatar.ShowBody(chase); }
if (!chase)
{
_boom.localPosition = Vector3.zero;
_boom.localRotation = Quaternion.identity;
_chaseShown = 0f;
return;
}
var v = _vehicle;
float size = Mathf.Max(2f, v.length);
if (_chaseDist < 0f) _chaseDist = size * 2.4f + 2f;
_chaseDist = Mathf.Clamp(_chaseDist - Ctl.Scroll * 0.9f, size + 1.5f, size * 5f + 6f);
var up = Planet.Up(v.transform.position);
var target = v.transform.position + up * (1.2f + v.length * 0.12f);
var look = head.rotation;
var back = -(look * Vector3.forward);
// a little higher than the eyes: the machine stays in front, not under the lens
var dir = (back + up * 0.25f).normalized;
float want = _chaseDist;
float reach = want;
int count = Physics.SphereCastNonAlloc(target, 0.35f, dir, s_boomHits, want, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore);
for (int i = 0; i < count; i++)
{
var h = s_boomHits[i];
if (h.distance > 0f && !h.collider.transform.IsChildOf(v.transform)) reach = Mathf.Min(reach, h.distance - 0.2f);
}
reach = Mathf.Max(1.5f, reach);
// closing in is instant (walls), backing off again is gentle
_chaseShown = _chaseShown <= 0f || reach < _chaseShown ? reach : Mathf.Lerp(_chaseShown, reach, Time.deltaTime * 4f);
var pos = target + dir * _chaseShown;
float clear = Planet.Altitude(pos);
if (clear < 0.7f) pos += Planet.Up(pos) * (0.7f - clear);
_boom.position = pos;
_boom.rotation = Quaternion.LookRotation(target - pos, up);
}
static readonly RaycastHit[] s_boomHits = new RaycastHit[32];
void EnterVehicle(Vehicle v)
{
SetFlying(false);
_vehicle = v;
Driving.Value = true;
Body.enabled = false;
_swimming = false;
_climbT = -1f;
Grab.Drop();
_heading = Heading(v);
_frame = _heading;
Sfx.Play("build_place", 0.5f, 1.3f);
Assistant.Say("asst_drive");
Hud.Toast(v.CanAuto ? Loc.T("WASD to drive · SHIFT boost · R chase view · E to hop off · C autopilot") : Loc.T("WASD to drive · SHIFT boost · R chase view · E to hop off"), Hud.ToastKind.Info);
}
void ExitVehicle()
{
if (!_vehicle) return;
if (Avatar && _bodyShown) { _bodyShown = false; Avatar.ShowBody(false); }
var v = _vehicle;
_vehicle = null;
Driving.Value = false;
// step off beside the vehicle (onto the deck if it is there, otherwise into the grass)
var up = Planet.Up(v.transform.position);
var side = v.transform.position + v.transform.right * (v.width + 0.9f) + up * 2f;
var pos = Planet.Surface(side) + up * 0.1f;
if (Physics.Raycast(side, -up, out var hit, 6f, (1 << Layers.Default) | (1 << Layers.Build), QueryTriggerInteraction.Ignore)) pos = hit.point + up * 0.1f;
Teleport(pos);
}
void UpdateRiding()
{
if (!_vehicle) return;
var v = _vehicle;
float speed = v.Body ? v.Body.linearVelocity.magnitude : 0f;
CameraFx.FovTarget(Mathf.Clamp01(speed / 15f) * 10f);
if (speed > 9f) CameraFx.Shake(0.004f * speed);
}
/// <summary>The machine's heading, stood upright on the planet.</summary>
static Quaternion Heading(Vehicle v)
{
var up = Planet.Up(v.transform.position);
return Quaternion.LookRotation(Vector3.ProjectOnPlane(v.transform.forward, up), up);
}
void FollowSeat()
{
transform.position = _vehicle.Seat.position - transform.up * 0.15f;
var heading = Heading(_vehicle);
// the view turns with the machine
_frame = heading * Quaternion.Inverse(_heading) * _frame;
_heading = heading;
transform.rotation = heading;
}
}
}