using System.Collections.Generic; using Unity.Collections; using Unity.Netcode; using UnityEngine; namespace GrassCutter { /// /// 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). /// [RequireComponent(typeof(CrewBody))] public class PlayerAgent : NetworkBehaviour, ICrewPose { public static readonly List All = new List(); 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 }; public readonly NetworkVariable NetName = new NetworkVariable("", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable SteamId = new NetworkVariable(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable ColorIndex = new NetworkVariable(); /// Which of the this player goes as. public readonly NetworkVariable Character = new NetworkVariable(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable Pitch = new NetworkVariable(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable ToolNet = new NetworkVariable(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable Driving = new NetworkVariable(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable Swimming = new NetworkVariable(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); /// Phone in hand, for the others to see. What's on it stays private. public readonly NetworkVariable PhoneOut = new NetworkVariable(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable Jetting = new NetworkVariable(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); /// Kilos in the container of the tool in hand. public readonly NetworkVariable Tank = new NetworkVariable(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); /// Cutting right now: where the blade is, w = strip width (0 = not cutting). Remote clients mow the same strip. public readonly NetworkVariable CutAt = new NetworkVariable(Vector4.zero, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); /// Bit per / this player has: tools are personal, upgrades shared. public readonly NetworkVariable Owned = new NetworkVariable(); public readonly NetworkVariable BeltSlots = new NetworkVariable(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; /// Standing down in the meadow (not on the deck): tall grass slows you, In The Weeds speeds up mowing. 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; /// Gravity boots on: Earth's pull instead of Herbaria's. public bool BootsOn { get; set; } /// Key of this player's tools in the host's save. public string SaveId { get; private set; } public bool ClaimedSave => SaveId != null; public Vehicle Vehicle => _vehicle; // interaction public RaycastHit AimHit { get; private set; } /// The built piece in the crosshair, if it has anything to set (not the company's). public BuildPiece AimPiece { get { if (!HasAim || !AimHit.collider) return null; var p = AimHit.collider.GetComponentInParent(); return p && !p.Def.company && (p.Upgrades != UpgradeKind.None || p.GetComponentInChildren() != 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; /// Where we stand and face: its up is always the planet's up here, turned by the mouse. Quaternion _frame = Quaternion.identity; Quaternion _heading = Quaternion.identity; Unity.Netcode.Components.NetworkTransform _net; bool _settled; float _pitch; Vector3 _vel; float _launchUntil; /// Something throws you (a twister): you fly loose for a moment and steering barely counts. 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; float _jumpTapAt = -9f, _dashAt = -9f; Vehicle _vehicle; public bool Flying { get; private set; } public float CheatSpeed = 1f; TeamState Ts => TeamState.Instance; public void SetFlying(bool on) { if (!IsOwner || _vehicle || 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; bool _wasGrounded = true; void Awake() { Body = GetComponent(); _net = GetComponent(); Body.Bumped += Bump; Tools = GetComponent(); Grab = GetComponent(); Avatar = GetComponentInChildren(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) { SaveId = id.ToString(); if (Ts && OwnerClientId != NetworkManager.ServerClientId && Ts.Banned(SaveId)) { NetworkManager.DisconnectClient(OwnerClientId, Loc.Pack("You are banned from this game")); return; } 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); } /// The travel terminal sends you here. [Rpc(SendTo.Owner)] public void ArriveRpc(Vector3 at) { Teleport(at); Sfx.Play("ui_open", 0.8f, 0.6f); } /// This player bought a treat: everyone else sees the machine do its show, and smoke or bubbles off them for a while. [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; /// Someone else on a treat: a puff of smoke from the cigar smoker now and then, bubbles off the beer drinker. 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(); 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 && !_vehicle; _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; } /// Which way is up for the crewman now (eased, so stepping on and off the deck doesn't jolt the view). Vector3 _stand; /// /// 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. /// 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; } /// 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. Transform _boom; /// Remembered between rides and runs: whoever likes the chase view gets it every time. 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 (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 && !_vehicle && AimPiece && !(PlayerBuild.Local && PlayerBuild.Local.Active)) UIRoot.I?.OpenPiece(AimPiece); // never lost under the soil if (!Flying && !_vehicle && 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 (!_vehicle) transform.rotation = _frame; float flat = Vector3.ProjectOnPlane(_vel, up).magnitude; float bob = (Grounded || _swimming) && !_vehicle ? Mathf.Sin(_bobPhase * 2f) * (_swimming ? 0.05f : 0.035f) * Mathf.Clamp01(flat / sprintSpeed + (_swimming ? 0.4f : 0f)) : 0f; float roll = -Ctl.Move.x * 1.5f; 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 (_vehicle) { // 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); } /// From the meadow: is the deck (or a vehicle) edge right in front of us? Then climb up onto it. 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.25f; _climbT = 0f; 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; } /// On the deck, facing an open edge railing: vault over it down into the meadow. 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; Body.enabled = false; Sfx.Play("jump", 0.55f, 1f); Avatar?.Squash(0.15f); return true; } void Climb() { _climbT += Time.deltaTime / 0.55f; float k = Mathf.Clamp01(_climbT); 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(); 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 || _vehicle) 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() == this) return; var grab = hit.collider.GetComponentInParent(); // 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(); AimGrabbable = grab; } } void DoInteract() { if (_vehicle) { _vehicle.RequestExit(); return; } if (Grab.Holding) { var bundle = Grab.Held ? Grab.Held.GetComponent() : 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().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(); Boom(); } /// /// 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. /// 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); } /// The machine's heading, stood upright on the planet. 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; } } }