Files
grass-cutters/Assets/Scripts/Gameplay/Grabbable.cs
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:44:40 +06:00

211 lines
7.7 KiB
C#

using System.Collections.Generic;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// A physics prop that players can pick up, carry and throw. Ownership moves to whoever grabs it so the
/// holder simulates it locally (no lag); NetworkTransform runs in owner-authority mode.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class Grabbable : NetworkBehaviour
{
public static readonly List<Grabbable> All = new List<Grabbable>();
public const ulong Nobody = ulong.MaxValue;
public string displayName = "Thing";
public bool trash;
public bool trashIsBox;
public float holdDistance = 1.4f;
/// <summary>Recycler payout multiplier (pallets are worth more than a wrap ball).</summary>
public float valueMul = 1f;
public readonly NetworkVariable<ulong> Holder = new NetworkVariable<ulong>(Nobody);
public readonly NetworkVariable<bool> IsTrashNet = new NetworkVariable<bool>();
public readonly NetworkVariable<float> Scale = new NetworkVariable<float>(1f);
public Rigidbody Body { get; private set; }
public bool IsTrash => trash || IsTrashNet.Value;
public bool IsHeld => Holder.Value != Nobody;
public bool Consumed { get; set; }
int _baseLayer;
Vector3 _baseScale;
void Awake()
{
Body = GetComponent<Rigidbody>();
Body.useGravity = false;
_baseLayer = gameObject.layer;
_baseScale = transform.localScale;
}
public override void OnNetworkSpawn()
{
All.Add(this);
Holder.OnValueChanged += (_, h) => ApplyHeldLayer(h != Nobody);
Scale.OnValueChanged += (_, s) => transform.localScale = _baseScale * s;
transform.localScale = _baseScale * Scale.Value;
ApplyHeldLayer(IsHeld);
}
public override void OnNetworkDespawn() { All.Remove(this); }
public override void OnDestroy()
{
All.Remove(this);
base.OnDestroy();
}
void ApplyHeldLayer(bool held)
{
int layer = held ? Layers.Held : _baseLayer;
foreach (var t in GetComponentsInChildren<Transform>(true)) t.gameObject.layer = layer;
}
// ───────────────────────── grabbing ─────────────────────────
public void RequestGrab()
{
if (IsHeld) return;
GrabRpc();
}
[Rpc(SendTo.Server)]
void GrabRpc(RpcParams rpc = default)
{
if (IsHeld || Consumed) return;
// grabbing something off a belt unlocks it from the queue
var cargo = GetComponent<Cargo>();
if (cargo && cargo.Belt) cargo.ServerLeaveBelt(Vector3.zero);
ulong who = rpc.Receive.SenderClientId;
Holder.Value = who;
if (OwnerClientId != who) NetworkObject.ChangeOwnership(who);
GrabbedRpc(who);
}
[Rpc(SendTo.Everyone)]
void GrabbedRpc(ulong who)
{
Sfx.PlayAt(GrabClip, transform.position, 0.7f, 1.1f);
if (who == NetworkManager.LocalClientId) PlayerAgent.Local?.Grab.OnGrantedGrab(this);
}
/// <summary>Called by the holder (owner) to let go; velocity is applied locally since the holder owns the body.</summary>
public void Release(Vector3 velocity, Vector3 angular)
{
if (IsOwner && Body && !Body.isKinematic)
{
Body.linearVelocity = velocity;
Body.angularVelocity = angular;
}
ReleaseRpc();
}
[Rpc(SendTo.Server)]
void ReleaseRpc(RpcParams rpc = default)
{
if (Holder.Value == rpc.Receive.SenderClientId) Holder.Value = Nobody;
}
/// <summary>Server: forcibly drop (e.g. the holder disconnected or the item got recycled).</summary>
public void ServerForceRelease()
{
if (IsServer) Holder.Value = Nobody;
}
/// <summary>Ask the owner to apply an impulse (used by the recycler to spit out non-trash).</summary>
public void ServerKick(Vector3 velocity)
{
KickRpc(velocity, RpcTarget.Single(OwnerClientId, RpcTargetUse.Temp));
}
[Rpc(SendTo.SpecifiedInParams)]
void KickRpc(Vector3 velocity, RpcParams p = default)
{
if (Body && !Body.isKinematic) { Body.linearVelocity = velocity; Body.angularVelocity = Random.insideUnitSphere * 6f; }
}
string GrabClip
{
get
{
var c = GetComponent<Cargo>();
if (!c) return "plastic_grab";
return c.kind == CargoKind.Brick ? "ice_clink" : "barrel_clunk";
}
}
float _lastPush;
/// <summary>Nudge from a walking player. Applied directly when we simulate the body, otherwise forwarded to the owner.</summary>
public void Push(Vector3 velocity)
{
if (Time.time - _lastPush < 0.12f || !IsSpawned) return;
_lastPush = Time.time;
if (IsOwner) { if (Body && !Body.isKinematic) Body.AddForce(velocity, ForceMode.VelocityChange); }
else PushRpc(velocity);
}
[Rpc(SendTo.Owner)]
void PushRpc(Vector3 velocity)
{
if (Body && !Body.isKinematic && !IsHeld) Body.AddForce(velocity, ForceMode.VelocityChange);
}
void FixedUpdate()
{
if (!IsSpawned || !IsOwner || !Body || Body.isKinematic) return;
var p = Body.position;
var up = Planet.Up(p);
if (!IsHeld) Body.AddForce(-up * GameDefs.LowGravity, ForceMode.Acceleration);
// there is no collider under the grass: the soil is a number
var c = GetComponent<Cargo>();
float below = Planet.Altitude(p) - (c ? c.halfHeight : 0.3f);
if (below >= 0f) return;
Body.position = p - up * below;
var v = Body.linearVelocity;
float fall = Vector3.Dot(v, up);
if (fall < 0f) v -= up * fall;
Body.linearVelocity = v * 0.9f;
Body.angularVelocity *= 0.9f;
}
void OnCollisionEnter(Collision c)
{
float v = c.relativeVelocity.magnitude;
if (v < 2.2f || !IsSpawned) return;
string clip = GrabClip;
Sfx.PlayAt(clip, transform.position, Mathf.Clamp01(v / 8f) * 0.8f, 1f, 0.1f, 0.05f);
}
}
public static class Layers
{
public const int Default = 0;
public const int Player = 6;
public const int Wrap = 7;
public const int Prop = 8;
public const int Vehicle = 9;
public const int Held = 10;
public const int ViewModel = 11;
public const int LocalPlayer = 12;
public const int Build = 13;
public static void SetupCollisions()
{
Physics.IgnoreLayerCollision(Held, Player);
Physics.IgnoreLayerCollision(Held, LocalPlayer);
Physics.IgnoreLayerCollision(Held, Held);
Physics.IgnoreLayerCollision(Wrap, Vehicle);
Physics.IgnoreLayerCollision(ViewModel, Default);
for (int i = 0; i < 32; i++) Physics.IgnoreLayerCollision(ViewModel, i);
}
/// <summary>Things the player's interaction ray can hit.</summary>
public static readonly int InteractMask = (1 << Default) | (1 << Wrap) | (1 << Prop) | (1 << Vehicle) | (1 << Player) | (1 << Build);
}
}