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>
This commit is contained in:
58
Assets/Scripts/Gameplay/BeltMerger.cs
Normal file
58
Assets/Scripts/Gameplay/BeltMerger.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Up to three belts come in, from the left, the right and the back, and one goes out of the front. They take turns, and a
|
||||
/// side with nothing waiting doesn't hold up the others. E gives one of the three the right of way.
|
||||
/// </summary>
|
||||
public class BeltMerger : Conveyor, IJunction
|
||||
{
|
||||
const float Wait = 0.1f;
|
||||
|
||||
int _last = -1;
|
||||
readonly float[] _tried = { -9f, -9f, -9f };
|
||||
|
||||
public int ModeCount => 4;
|
||||
public string ModeName(int mode) => mode == 0 ? Loc.T("the belts take turns") : mode == 1 ? Loc.T("the left belt goes first") : mode == 2 ? Loc.T("the right belt goes first") : Loc.T("the back belt goes first");
|
||||
public Color ModeColor(int mode) => mode == 0 ? Color.white : new Color(0.3f, 0.6f, 0.95f);
|
||||
|
||||
// route 0 = in from the left, route 1 = in from the right, route 2 = in from the back
|
||||
protected override int RouteCount => 3;
|
||||
static float Side(int route) => route == 0 ? -1f : route == 1 ? 1f : 0f;
|
||||
|
||||
protected override Vector2 PathAt(float d, int route) =>
|
||||
d < 0.5f && route != 2 ? new Vector2(Side(route) * (0.5f - d), 0f) : new Vector2(0f, d - 0.5f);
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
for (int r = 0; r < 3; r++)
|
||||
into.Add(new Port { at = WorldOnPath(0f, r, 0f), dir = r == 2 ? transform.forward : transform.right * -Side(r), input = true });
|
||||
into.Add(new Port { at = WorldOnPath(1f, 0, 0f), dir = transform.forward });
|
||||
}
|
||||
|
||||
protected override bool Takes(int port)
|
||||
{
|
||||
_tried[port] = Time.time;
|
||||
int first = Mode - 1;
|
||||
if (first >= 0) return port == first || Time.time - _tried[first] > Wait;
|
||||
for (int k = 1; k <= 3; k++)
|
||||
{
|
||||
int other = (_last + 3 + k) % 3;
|
||||
if (other == port) return true;
|
||||
if (Time.time - _tried[other] < Wait) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override int EntryRoute(Cargo c, int port)
|
||||
{
|
||||
_last = port;
|
||||
Sfx.PlayAt("merger_clunk", transform.position + transform.up * 0.4f, 0.35f, 1f, 0.08f, 0.25f);
|
||||
return port;
|
||||
}
|
||||
|
||||
protected override int RouteAt(Vector2 local, Cargo c) => local.x < -0.1f ? 0 : local.x > 0.1f ? 1 : 2;
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BeltMerger.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BeltMerger.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c330fdcc26d479d418a98a52d4ad19a4
|
||||
647
Assets/Scripts/Gameplay/BeltRun.cs
Normal file
647
Assets/Scripts/Gameplay/BeltRun.cs
Normal file
@ -0,0 +1,647 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// One belt from A to B, up to 30 m, at any height. The piece stands at A with +Z toward B; the bed, the rails and the posts
|
||||
/// down to the ground are generated to fit, so they can only be built once the ends are known. Where it meets another belt
|
||||
/// at an angle the two of them sweep round one arc between them, and where it comes out of (or goes into) a machine's port
|
||||
/// at an angle it leaves the way the port faces and bends round to the run. Cargo rides the same curve the belt is drawn on.
|
||||
/// </summary>
|
||||
public class BeltRun : Conveyor
|
||||
{
|
||||
float _len = 1f;
|
||||
BeltShape _shape;
|
||||
|
||||
protected override float Surface => 0f;
|
||||
protected override bool Sides => true;
|
||||
protected override float Length(int route) => _shape != null ? _shape.PathLength : _len;
|
||||
protected override Vector2 PathAt(float d, int route) => _shape != null ? _shape.PathAt(d) : new Vector2(0f, d);
|
||||
protected override float HeightAt(float d, int route) => _shape != null ? _shape.HeightAt(d) : 0f;
|
||||
|
||||
protected override void Project(Vector2 local, out int route, out float d)
|
||||
{
|
||||
route = 0;
|
||||
d = _shape != null ? _shape.Project(local) : Mathf.Clamp(local.y, 0f, _len);
|
||||
}
|
||||
|
||||
public float Metres => _len;
|
||||
/// <summary>Where the run was laid to. Belts and machines join here, however the belt itself bends round to meet them.</summary>
|
||||
public Vector3 End => transform.position + transform.rotation * new Vector3(0f, 0f, _len);
|
||||
/// <summary>Where the run was laid from.</summary>
|
||||
public Vector3 StartPoint => transform.position;
|
||||
|
||||
protected override Vector3 ExitAt(int route) => End;
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(new Port { at = StartPoint, dir = Tangent(0f, 0), input = true });
|
||||
into.Add(new Port { at = End, dir = Tangent(Length(0), 0) });
|
||||
}
|
||||
|
||||
Vector3 _from, _to;
|
||||
int _seenVersion = -1;
|
||||
float _nextLook;
|
||||
|
||||
/// <summary>
|
||||
/// How each end meets its neighbours, redone whenever something is built or taken down nearby: a belt running on gets
|
||||
/// half of a rounded corner, a machine's port gets a bend out of it and a hood over the end, a free end keeps its drum.
|
||||
/// </summary>
|
||||
protected override void Update()
|
||||
{
|
||||
base.Update();
|
||||
if (_shape == null || BuildPiece.Version == _seenVersion || Time.time < _nextLook) return;
|
||||
_seenVersion = BuildPiece.Version;
|
||||
_nextLook = Time.time + 0.25f;
|
||||
_shape.Fit(_from, _to, JointAt(End, true, this, Piece), JointAt(StartPoint, false, this, Piece));
|
||||
}
|
||||
|
||||
/// <summary>What a belt end at <paramref name="at"/> meets (the ghost in the player's hands asks too, with no belt of its own).</summary>
|
||||
public static BeltShape.Joint JointAt(Vector3 at, bool end, BeltRun self, BuildPiece skip)
|
||||
{
|
||||
foreach (var c in All)
|
||||
{
|
||||
if (!(c is BeltRun r) || r == self || r._shape == null) continue;
|
||||
if (((end ? r.StartPoint : r.End) - at).sqrMagnitude < BeltNet.Joined * BeltNet.Joined)
|
||||
return new BeltShape.Joint { kind = BeltShape.JointKind.Belt, dir = r.transform.forward, len = r._len };
|
||||
}
|
||||
// a splitter or merger is a belt too: the end bends round to its port, but keeps its drum instead of a hood
|
||||
if (BeltNet.Nearest(at, end, BeltNet.Joined, skip, out var piece, out _, out var port))
|
||||
return new BeltShape.Joint { kind = BeltShape.JointKind.Port, dir = port.dir, bare = piece.GetComponentInChildren<Conveyor>() };
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>Stretches everything to the run. Every peer does this when the piece spawns.</summary>
|
||||
public void Lay(Vector3 from, Vector3 to)
|
||||
{
|
||||
_len = Vector3.Distance(from, to);
|
||||
_from = from;
|
||||
_to = to;
|
||||
_seenVersion = -1;
|
||||
var root = Piece.transform;
|
||||
if (_shape == null)
|
||||
{
|
||||
_shape = new BeltShape(root, root.gameObject.layer);
|
||||
belts = new[] { _shape.Rubber };
|
||||
}
|
||||
_shape.Fit(from, to);
|
||||
var trigger = GetComponent<BoxCollider>();
|
||||
trigger.center = new Vector3(0f, 0.25f, _len * 0.5f);
|
||||
trigger.size = new Vector3(0.92f, 0.5f, _len);
|
||||
Bar("BeltBase", new Vector3(0f, -0.07f, _len * 0.5f), new Vector3(1f, 0.14f, _len));
|
||||
Bar("RailL", new Vector3(-0.47f, 0.07f, _len * 0.5f), new Vector3(0.06f, 0.14f, _len));
|
||||
Bar("RailR", new Vector3(0.47f, 0.07f, _len * 0.5f), new Vector3(0.06f, 0.14f, _len));
|
||||
}
|
||||
|
||||
void Bar(string name, Vector3 at, Vector3 size)
|
||||
{
|
||||
var t = Piece.transform.Find(name);
|
||||
if (!t) return;
|
||||
t.localPosition = at;
|
||||
t.GetComponent<BoxCollider>().size = size;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The look of a belt run, shared by the built thing and the ghost in the player's hands, and the path it runs along.</summary>
|
||||
public class BeltShape
|
||||
{
|
||||
const float PostEvery = 6f, BracketEvery = 1.5f, BedTop = -0.02f, BedLow = -0.14f, DrumR = 0.1f, RailX = 0.47f;
|
||||
/// <summary>How wide a bend sweeps round, measured to the middle of the belt.</summary>
|
||||
const float Radius = 1.4f;
|
||||
/// <summary>Degrees of arc per step: small enough that the rails read as one smooth curve.</summary>
|
||||
const float ArcStep = 5f;
|
||||
|
||||
public readonly MeshRenderer Frame, Iron, Rubber;
|
||||
readonly Mesh _frame = new Mesh { name = "BeltFrame" }, _iron = new Mesh { name = "BeltIron" }, _rubber = new Mesh { name = "BeltRubber" };
|
||||
readonly List<Vector3> _v = new List<Vector3>(), _n = new List<Vector3>();
|
||||
readonly List<Vector2> _uv = new List<Vector2>();
|
||||
readonly List<int> _t = new List<int>();
|
||||
/// <summary>The centre line in the run's own space (flat, +Z toward B), how far along it each point is, and its right-hand side at each point (longer than 1 where it turns, so the edges stay parallel).</summary>
|
||||
readonly List<Vector3> _path = new List<Vector3>(), _side = new List<Vector3>();
|
||||
/// <summary>At each point of the path: which way it runs (in 3D, so up and down slopes too), and the belt's own up,
|
||||
/// square to that and to the planet's up. Two belts meeting at a corner work these out the same way at the same spot,
|
||||
/// so their rails and bed meet edge to edge.</summary>
|
||||
readonly List<Vector3> _tan = new List<Vector3>(), _up = new List<Vector3>();
|
||||
readonly List<float> _along = new List<float>();
|
||||
static readonly List<Vector3> s_head = new List<Vector3>(), s_tail = new List<Vector3>(), s_headT = new List<Vector3>(), s_tailT = new List<Vector3>();
|
||||
/// <summary>Where the next parts go: a drum, a hood or a bracket is made square and put down along the path.</summary>
|
||||
Matrix4x4 _xf = Matrix4x4.identity;
|
||||
|
||||
public BeltShape(Transform parent, int layer)
|
||||
{
|
||||
Frame = Part("Frame", parent, layer, _frame, BuildLook.Mat("M_Timber", new Color(0.55f, 0.4f, 0.25f)));
|
||||
Iron = Part("Iron", parent, layer, _iron, BuildLook.Mat("M_Steel", new Color(0.55f, 0.57f, 0.6f)));
|
||||
Rubber = Part("Rubber", parent, layer, _rubber, BuildLook.Mat("M_ConveyorBelt", new Color(0.16f, 0.16f, 0.17f)));
|
||||
}
|
||||
|
||||
static MeshRenderer Part(string name, Transform parent, int layer, Mesh mesh, Material mat)
|
||||
{
|
||||
var go = new GameObject(name) { layer = layer };
|
||||
go.transform.SetParent(parent, false);
|
||||
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
||||
var r = go.AddComponent<MeshRenderer>();
|
||||
r.sharedMaterial = mat;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>The ghost is all one see-through material and casts no shadow.</summary>
|
||||
public void Paint(Material m)
|
||||
{
|
||||
foreach (var r in new[] { Frame, Iron, Rubber })
|
||||
{
|
||||
r.sharedMaterial = m;
|
||||
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
}
|
||||
}
|
||||
|
||||
public void Destroy()
|
||||
{
|
||||
Object.Destroy(_frame);
|
||||
Object.Destroy(_iron);
|
||||
Object.Destroy(_rubber);
|
||||
}
|
||||
|
||||
// ───────────────────────── the path ─────────────────────────
|
||||
|
||||
public float PathLength => _along.Count > 0 ? _along[_along.Count - 1] : 0f;
|
||||
|
||||
/// <summary>The point d metres along the path, in the run's space (x across, y along the run).</summary>
|
||||
public Vector2 PathAt(float d)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n == 0) return new Vector2(0f, d);
|
||||
if (d <= 0f) return Flat(_path[0]);
|
||||
for (int i = 1; i < n; i++)
|
||||
if (d <= _along[i]) return Flat(Vector3.Lerp(_path[i - 1], _path[i], Mathf.InverseLerp(_along[i - 1], _along[i], d)));
|
||||
return Flat(_path[n - 1]);
|
||||
}
|
||||
|
||||
/// <summary>How high the centre line is d metres along, in the run's space (it rounds over a change of slope).</summary>
|
||||
public float HeightAt(float d)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n == 0 || d <= 0f) return n == 0 ? 0f : _path[0].y;
|
||||
for (int i = 1; i < n; i++)
|
||||
if (d <= _along[i]) return Mathf.Lerp(_path[i - 1].y, _path[i].y, Mathf.InverseLerp(_along[i - 1], _along[i], d));
|
||||
return _path[n - 1].y;
|
||||
}
|
||||
|
||||
/// <summary>How far along the path its nearest point to a local point is.</summary>
|
||||
public float Project(Vector2 local)
|
||||
{
|
||||
if (_path.Count < 2) return 0f;
|
||||
float best = float.MaxValue, d = 0f;
|
||||
for (int i = 1; i < _path.Count; i++)
|
||||
{
|
||||
var a = Flat(_path[i - 1]);
|
||||
var ab = Flat(_path[i]) - a;
|
||||
float k = ab.sqrMagnitude > 1e-8f ? Mathf.Clamp01(Vector2.Dot(local - a, ab) / ab.sqrMagnitude) : 0f;
|
||||
float e = (a + ab * k - local).sqrMagnitude;
|
||||
if (e < best) { best = e; d = Mathf.Lerp(_along[i - 1], _along[i], k); }
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static Vector2 Flat(Vector3 p) => new Vector2(p.x, p.z);
|
||||
Vector3 At(float d) { var p = PathAt(d); return new Vector3(p.x, 0f, p.y); }
|
||||
|
||||
Vector3 Fwd(float d)
|
||||
{
|
||||
float L = PathLength;
|
||||
var p = PathAt(Mathf.Clamp(d + 0.03f, 0f, L)) - PathAt(Mathf.Clamp(d - 0.03f, 0f, L));
|
||||
return p.sqrMagnitude > 1e-8f ? new Vector3(p.x, 0f, p.y).normalized : Vector3.forward;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lays out the centre line: a straight run, with half of a corner arc at an end that meets another belt (that belt draws
|
||||
/// the other half, so the two halves meet in the middle of the arc), or a bend out of a port at an end that meets a machine.
|
||||
/// </summary>
|
||||
void Route(float len, Vector3 a, Quaternion rot, Joint atEnd, Joint atStart)
|
||||
{
|
||||
var inv = Quaternion.Inverse(rot);
|
||||
_path.Clear();
|
||||
_tan.Clear();
|
||||
_along.Clear();
|
||||
s_head.Clear();
|
||||
s_tail.Clear();
|
||||
s_headT.Clear();
|
||||
s_tailT.Clear();
|
||||
var b = new Vector3(0f, 0f, len);
|
||||
// a corner with the belt before or after: one arc between the two runs, in 3D, so a change of slope is rounded too
|
||||
if (atStart.kind == JointKind.Belt) Corner(inv * atStart.dir, Vector3.forward, Mathf.Min(len, atStart.len), Vector3.zero, false, s_head, s_headT);
|
||||
if (atEnd.kind == JointKind.Belt) Corner(Vector3.forward, inv * atEnd.dir, Mathf.Min(len, atEnd.len), b, true, s_tail, s_tailT);
|
||||
bool portStart = atStart.kind == JointKind.Port && atStart.dir.sqrMagnitude > 1e-4f;
|
||||
bool portEnd = atEnd.kind == JointKind.Port && atEnd.dir.sqrMagnitude > 1e-4f;
|
||||
// a bend at both ends: each one aims for where the other one leaves off, and they settle in a couple of rounds
|
||||
for (int pass = 0; pass < (portStart && portEnd ? 3 : 1); pass++)
|
||||
{
|
||||
if (portStart)
|
||||
{
|
||||
s_head.Clear();
|
||||
s_headT.Clear();
|
||||
if (!Bow(Vector3.zero, Level(inv * atStart.dir), s_tail.Count > 0 ? s_tail[0] : b, s_head)) s_head.Clear();
|
||||
}
|
||||
if (portEnd)
|
||||
{
|
||||
s_tail.Clear();
|
||||
s_tailT.Clear();
|
||||
if (Bow(b, -Level(inv * atEnd.dir), s_head.Count > 0 ? s_head[s_head.Count - 1] : Vector3.zero, s_tail)) s_tail.Reverse();
|
||||
else s_tail.Clear();
|
||||
}
|
||||
}
|
||||
if (s_head.Count == 0) s_head.Add(Vector3.zero);
|
||||
if (s_tail.Count == 0) s_tail.Add(b);
|
||||
for (int i = 0; i < s_head.Count; i++) Add(s_head[i], i < s_headT.Count ? s_headT[i] : Vector3.zero);
|
||||
for (int i = 0; i < s_tail.Count; i++) Add(s_tail[i], i < s_tailT.Count ? s_tailT[i] : Vector3.zero);
|
||||
Frames(a, rot, inv);
|
||||
}
|
||||
|
||||
static Vector3 Level(Vector3 v) => new Vector3(v.x, 0f, v.z).normalized;
|
||||
|
||||
void Add(Vector3 p, Vector3 tangent)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n > 0 && (p - _path[n - 1]).sqrMagnitude < 1e-6f)
|
||||
{
|
||||
if (tangent.sqrMagnitude > 1e-6f) _tan[n - 1] = tangent;
|
||||
return;
|
||||
}
|
||||
_along.Add(n == 0 ? 0f : _along[n - 1] + Vector3.Distance(p, _path[n - 1]));
|
||||
_path.Add(p);
|
||||
_tan.Add(tangent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Half of the arc round a corner at <paramref name="j"/>, where a run heading <paramref name="d1"/> meets one heading
|
||||
/// <paramref name="d2"/> (in 3D: a turn, a change of slope, or both). The arc lies in the plane of the two directions and
|
||||
/// touches both runs; the end's half runs from where it leaves this run to its middle, the start's half from the middle
|
||||
/// onto this run. Both belts work it out from the same directions, corner and shorter length, so the halves meet exactly.
|
||||
/// </summary>
|
||||
static void Corner(Vector3 d1, Vector3 d2, float shortest, Vector3 j, bool atEnd, List<Vector3> into, List<Vector3> tangents)
|
||||
{
|
||||
d1.Normalize();
|
||||
d2.Normalize();
|
||||
float theta = Mathf.Min(Vector3.Angle(d1, d2), 150f);
|
||||
if (theta < 2f) return;
|
||||
float half = theta * 0.5f * Mathf.Deg2Rad, th = theta * Mathf.Deg2Rad;
|
||||
float tanH = Mathf.Tan(half);
|
||||
float cut = Mathf.Min(Radius * tanH, shortest * 0.5f);
|
||||
float r = cut / tanH;
|
||||
var inward = (d2 - d1 * Vector3.Dot(d1, d2)).normalized;
|
||||
var c = j - d1 * cut + inward * r;
|
||||
int steps = Mathf.Max(2, Mathf.CeilToInt(theta * 0.5f / ArcStep));
|
||||
for (int i = 0; i <= steps; i++)
|
||||
{
|
||||
float k = (float)i / steps;
|
||||
float phi = atEnd ? th * 0.5f * k : th * 0.5f * (1f + k);
|
||||
into.Add(c - inward * r * Mathf.Cos(phi) + d1 * r * Mathf.Sin(phi));
|
||||
tangents.Add((inward * Mathf.Sin(phi) + d1 * Mathf.Cos(phi)).normalized);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An arc that leaves <paramref name="at"/> heading <paramref name="heading"/> and turns until it heads straight for
|
||||
/// <paramref name="target"/> (false: no bend needed, or no room for one).
|
||||
/// </summary>
|
||||
static bool Bow(Vector3 at, Vector3 heading, Vector3 target, List<Vector3> into)
|
||||
{
|
||||
var to = target - at;
|
||||
to.y = 0f;
|
||||
if (heading.sqrMagnitude < 1e-4f || to.sqrMagnitude < 0.25f) return false;
|
||||
float turn = Vector3.SignedAngle(heading, to, Vector3.up);
|
||||
if (Mathf.Abs(turn) < 3f || Mathf.Abs(turn) > 165f) return false;
|
||||
float s = Mathf.Sign(turn);
|
||||
float r = Mathf.Min(Radius, to.magnitude * 0.4f);
|
||||
if (r < 0.6f) return false;
|
||||
var c = at + Quaternion.AngleAxis(90f * s, Vector3.up) * heading * r;
|
||||
var w = target - c;
|
||||
w.y = 0f;
|
||||
float dist = w.magnitude;
|
||||
if (dist <= r * 1.05f) return false;
|
||||
float alpha = Mathf.Acos(r / dist) * Mathf.Rad2Deg;
|
||||
var spoke = at - c;
|
||||
var end = Vector3.zero;
|
||||
float fit = -2f;
|
||||
foreach (float sign in new[] { -1f, 1f })
|
||||
{
|
||||
var rt = Quaternion.AngleAxis(alpha * sign, Vector3.up) * (w / dist) * r;
|
||||
// which way the arc is heading where it leaves the circle
|
||||
var h = Quaternion.AngleAxis(90f * s, Vector3.up) * rt.normalized;
|
||||
float f = Vector3.Dot(h, (target - (c + rt)).normalized);
|
||||
if (f > fit) { fit = f; end = rt; }
|
||||
}
|
||||
if (fit < 0.95f) return false;
|
||||
float sweep = Vector3.SignedAngle(spoke, end, Vector3.up);
|
||||
if (sweep * s < 0f) sweep += 360f * s;
|
||||
if (Mathf.Abs(sweep) > 200f) return false;
|
||||
int steps = Mathf.Max(2, Mathf.CeilToInt(Mathf.Abs(sweep) / ArcStep));
|
||||
for (int i = 0; i <= steps; i++) into.Add(c + Quaternion.AngleAxis(sweep * i / steps, Vector3.up) * spoke);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frame at each point of the path: its direction (worked out from the neighbours where the route didn't give one),
|
||||
/// the right-hand side square to it and to the planet's up there, and the belt's own up square to both.
|
||||
/// </summary>
|
||||
void Frames(Vector3 a, Quaternion rot, Quaternion inv)
|
||||
{
|
||||
_side.Clear();
|
||||
_up.Clear();
|
||||
int n = _path.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var t = _tan[i];
|
||||
if (t.sqrMagnitude < 1e-6f)
|
||||
{
|
||||
var f = n < 2 ? Vector3.forward : _path[Mathf.Min(n - 1, i + 1)] - _path[Mathf.Max(0, i - 1)];
|
||||
t = f.sqrMagnitude > 1e-8f ? f.normalized : Vector3.forward;
|
||||
_tan[i] = t;
|
||||
}
|
||||
var planetUp = inv * Planet.Up(a + rot * _path[i]);
|
||||
var side = Vector3.Cross(planetUp, t);
|
||||
side = side.sqrMagnitude > 1e-6f ? side.normalized : Vector3.right;
|
||||
_side.Add(side);
|
||||
_up.Add(Vector3.Cross(t, side).normalized);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── the meshes ─────────────────────────
|
||||
|
||||
void Begin()
|
||||
{
|
||||
_v.Clear(); _n.Clear(); _uv.Clear(); _t.Clear();
|
||||
_xf = Matrix4x4.identity;
|
||||
}
|
||||
|
||||
void Finish(Mesh m)
|
||||
{
|
||||
m.Clear();
|
||||
m.indexFormat = _v.Count > 60000 ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16;
|
||||
m.SetVertices(_v);
|
||||
m.SetNormals(_n);
|
||||
m.SetUVs(0, _uv);
|
||||
m.SetTriangles(_t, 0);
|
||||
m.RecalculateBounds();
|
||||
_xf = Matrix4x4.identity;
|
||||
}
|
||||
|
||||
/// <summary>Square parts that follow go down d metres along the path, turned and tilted with it.</summary>
|
||||
void Along(float d)
|
||||
{
|
||||
Frame3(d, out var at, out var fwd, out var up);
|
||||
_xf = Matrix4x4.TRS(at, Quaternion.LookRotation(fwd, up), Vector3.one);
|
||||
}
|
||||
|
||||
/// <summary>The point d metres along the path in 3D, with its direction and the belt's up there.</summary>
|
||||
void Frame3(float d, out Vector3 at, out Vector3 fwd, out Vector3 up)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n == 0) { at = new Vector3(0f, 0f, d); fwd = Vector3.forward; up = Vector3.up; return; }
|
||||
int i = 1;
|
||||
while (i < n - 1 && _along[i] < d) i++;
|
||||
float k = n < 2 ? 0f : Mathf.Clamp01(Mathf.InverseLerp(_along[i - 1], _along[i], d));
|
||||
int a = n < 2 ? 0 : i - 1, b = n < 2 ? 0 : i;
|
||||
at = Vector3.Lerp(_path[a], _path[b], k);
|
||||
fwd = Vector3.Slerp(_tan[a], _tan[b], k).normalized;
|
||||
up = Vector3.Slerp(_up[a], _up[b], k).normalized;
|
||||
}
|
||||
|
||||
void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 n, Vector2 uv0, Vector2 uv1)
|
||||
{
|
||||
Face(a, b, c, d, n, n, n, n, uv0, new Vector2(uv1.x, uv0.y), uv1, new Vector2(uv0.x, uv1.y));
|
||||
}
|
||||
|
||||
/// <summary>A four-cornered face given round its edge, facing whichever way its normals say.</summary>
|
||||
void Face(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 na, Vector3 nb, Vector3 nc, Vector3 nd, Vector2 ua, Vector2 ub, Vector2 uc, Vector2 ud)
|
||||
{
|
||||
int i = _v.Count;
|
||||
_v.Add(_xf.MultiplyPoint3x4(a)); _v.Add(_xf.MultiplyPoint3x4(b)); _v.Add(_xf.MultiplyPoint3x4(c)); _v.Add(_xf.MultiplyPoint3x4(d));
|
||||
_n.Add(_xf.MultiplyVector(na).normalized); _n.Add(_xf.MultiplyVector(nb).normalized);
|
||||
_n.Add(_xf.MultiplyVector(nc).normalized); _n.Add(_xf.MultiplyVector(nd).normalized);
|
||||
_uv.Add(ua); _uv.Add(ub); _uv.Add(uc); _uv.Add(ud);
|
||||
if (Vector3.Dot(Vector3.Cross(b - a, c - a), na + nb + nc + nd) < 0f)
|
||||
{
|
||||
_t.Add(i); _t.Add(i + 2); _t.Add(i + 1);
|
||||
_t.Add(i); _t.Add(i + 3); _t.Add(i + 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
_t.Add(i); _t.Add(i + 1); _t.Add(i + 2);
|
||||
_t.Add(i); _t.Add(i + 2); _t.Add(i + 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A bar of square section swept along the whole path, from x0 to x1 across and y0 to y1 up, its ends closed.</summary>
|
||||
bool _capStart = true, _capEnd = true;
|
||||
|
||||
void Sweep(float x0, float x1, float y0, float y1)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n < 2) return;
|
||||
float w = (x1 - x0) * 0.8f, h = (y1 - y0) * 0.8f;
|
||||
Vector3 P(int k, float x, float y) => _path[k] + _side[k] * x + _up[k] * y;
|
||||
for (int i = 0; i + 1 < n; i++)
|
||||
{
|
||||
int j = i + 1;
|
||||
float v0 = _along[i] * 0.8f, v1 = _along[j] * 0.8f;
|
||||
var si = _side[i];
|
||||
var sj = _side[j];
|
||||
var ui = _up[i];
|
||||
var uj = _up[j];
|
||||
Face(P(i, x0, y1), P(i, x1, y1), P(j, x1, y1), P(j, x0, y1), ui, ui, uj, uj, new Vector2(0f, v0), new Vector2(w, v0), new Vector2(w, v1), new Vector2(0f, v1));
|
||||
Face(P(i, x0, y0), P(i, x1, y0), P(j, x1, y0), P(j, x0, y0), -ui, -ui, -uj, -uj, new Vector2(0f, v0), new Vector2(w, v0), new Vector2(w, v1), new Vector2(0f, v1));
|
||||
Face(P(i, x1, y0), P(i, x1, y1), P(j, x1, y1), P(j, x1, y0), si, si, sj, sj, new Vector2(0f, v0), new Vector2(h, v0), new Vector2(h, v1), new Vector2(0f, v1));
|
||||
Face(P(i, x0, y0), P(i, x0, y1), P(j, x0, y1), P(j, x0, y0), -si, -si, -sj, -sj, new Vector2(0f, v0), new Vector2(h, v0), new Vector2(h, v1), new Vector2(0f, v1));
|
||||
}
|
||||
foreach (int k in new[] { 0, n - 1 })
|
||||
{
|
||||
if (k == 0 ? !_capStart : !_capEnd) continue;
|
||||
var f = _tan[k] * (k == 0 ? -1f : 1f);
|
||||
Quad(P(k, x0, y0), P(k, x1, y0), P(k, x1, y1), P(k, x0, y1), f, Vector2.zero, new Vector2(w, h));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The belt itself: one strip along the path, V in metres so the texture runs round the bends with it.</summary>
|
||||
void Strip(float half)
|
||||
{
|
||||
for (int i = 0; i + 1 < _path.Count; i++)
|
||||
{
|
||||
int j = i + 1;
|
||||
Face(_path[i] - _side[i] * half, _path[i] + _side[i] * half, _path[j] + _side[j] * half, _path[j] - _side[j] * half, _up[i], _up[i], _up[j], _up[j],
|
||||
new Vector2(0f, _along[i]), new Vector2(1f, _along[i]), new Vector2(1f, _along[j]), new Vector2(0f, _along[j]));
|
||||
}
|
||||
}
|
||||
|
||||
void Box(Vector3 center, Quaternion rot, Vector3 size)
|
||||
{
|
||||
for (int axis = 0; axis < 3; axis++)
|
||||
for (int sign = -1; sign <= 1; sign += 2)
|
||||
{
|
||||
var n = Vector3.zero; n[axis] = sign;
|
||||
var u = Vector3.zero; u[(axis + 1) % 3] = 1f;
|
||||
var v = Vector3.zero; v[(axis + 2) % 3] = 1f;
|
||||
if (sign > 0) { var w = u; u = v; v = w; }
|
||||
Vector3 P(float a, float b) => center + rot * Vector3.Scale((n + u * a + v * b) * 0.5f, size);
|
||||
// the grain runs the long way and the texture keeps its scale
|
||||
var tile = new Vector2(Vector3.Scale(u, size).magnitude, Vector3.Scale(v, size).magnitude) * 0.8f;
|
||||
Quad(P(-1, -1), P(1, -1), P(1, 1), P(-1, 1), rot * n, Vector2.zero, tile);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An eight-sided roller across the belt.</summary>
|
||||
void Drum(Vector3 center, float r, float width)
|
||||
{
|
||||
const int Sides = 8;
|
||||
for (int k = 0; k < Sides; k++)
|
||||
{
|
||||
float a0 = k * Mathf.PI * 2f / Sides, a1 = (k + 1) * Mathf.PI * 2f / Sides, mid = (a0 + a1) * 0.5f;
|
||||
Vector3 P(float ang, float x) => center + new Vector3(x, Mathf.Sin(ang) * r, Mathf.Cos(ang) * r);
|
||||
Quad(P(a0, -width * 0.5f), P(a0, width * 0.5f), P(a1, width * 0.5f), P(a1, -width * 0.5f), new Vector3(0f, Mathf.Sin(mid), Mathf.Cos(mid)), Vector2.zero, Vector2.one);
|
||||
}
|
||||
}
|
||||
|
||||
public enum JointKind { Free, Belt, Port }
|
||||
|
||||
/// <summary>What an end of the run meets: nothing, another belt (which way it runs, how long it is), or a machine's port (which way things flow through it).</summary>
|
||||
public struct Joint
|
||||
{
|
||||
public JointKind kind;
|
||||
public Vector3 dir;
|
||||
public float len;
|
||||
/// <summary>A port on another belt piece: no hood over the end.</summary>
|
||||
public bool bare;
|
||||
public bool Hooded => kind == JointKind.Port && !bare;
|
||||
public bool Drum => kind == JointKind.Free || (kind == JointKind.Port && bare);
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the meshes for a run from A to B, with the parent standing at A along the run.</summary>
|
||||
public void Fit(Vector3 a, Vector3 b) => Fit(a, b, default, default);
|
||||
|
||||
/// <summary>
|
||||
/// The same, knowing what each end meets. Bed, rails and belt are swept along one path, so a bend is one smooth piece:
|
||||
/// no wedges, no rails crossing, the belt's arrows running round it. Where it ends at a machine, a hood comes down over
|
||||
/// the end, as if the machine had drawn the belt in; a free end shows its drum.
|
||||
/// </summary>
|
||||
public void Fit(Vector3 a, Vector3 b, Joint atEnd, Joint atStart)
|
||||
{
|
||||
float len = Vector3.Distance(a, b);
|
||||
var rot = BuildRules.RunRotation(a, b);
|
||||
Route(len, a, rot, atEnd, atStart);
|
||||
float total = PathLength;
|
||||
// the belt before this one already stands a post and a bracket at the middle of the corner
|
||||
int first = atStart.kind == JointKind.Belt ? 1 : 0;
|
||||
_capStart = atStart.kind != JointKind.Belt;
|
||||
_capEnd = atEnd.kind != JointKind.Belt;
|
||||
|
||||
Begin();
|
||||
Sweep(-0.45f, 0.45f, BedLow, BedTop);
|
||||
Sweep(-RailX - 0.03f, -RailX + 0.03f, -0.05f, 0.15f);
|
||||
Sweep(RailX - 0.03f, RailX + 0.03f, -0.05f, 0.15f);
|
||||
int posts = Mathf.Max(1, Mathf.RoundToInt(total / PostEvery));
|
||||
for (int i = first; i <= posts; i++)
|
||||
{
|
||||
Frame3(total * i / posts, out var on, out var fwd, out var up);
|
||||
Post(a, rot, on + up * BedLow, fwd);
|
||||
}
|
||||
Finish(_frame);
|
||||
|
||||
Begin();
|
||||
if (atStart.Drum) { Along(0f); Drum(new Vector3(0f, -0.09f, 0f), DrumR, 0.9f); }
|
||||
if (atEnd.Drum) { Along(total); Drum(new Vector3(0f, -0.09f, 0f), DrumR, 0.9f); }
|
||||
int brackets = Mathf.Max(1, Mathf.RoundToInt(total / BracketEvery));
|
||||
for (int i = first; i <= brackets; i++)
|
||||
{
|
||||
Along(total * i / brackets);
|
||||
foreach (float x in new[] { -0.51f, 0.51f })
|
||||
Box(new Vector3(x, 0.05f, 0f), Quaternion.identity, new Vector3(0.02f, 0.24f, 0.09f));
|
||||
}
|
||||
if (atEnd.Hooded) { Along(total); Hood(0f, -1f); }
|
||||
if (atStart.Hooded) { Along(0f); Hood(0f, 1f); }
|
||||
Finish(_iron);
|
||||
|
||||
Begin();
|
||||
Strip(0.44f);
|
||||
Finish(_rubber);
|
||||
}
|
||||
|
||||
/// <summary>Degrees the next run turns away from this one, seen from above: + to the right.</summary>
|
||||
static float Turn(Vector3 localDir)
|
||||
{
|
||||
var flat = new Vector3(localDir.x, 0f, localDir.z);
|
||||
if (flat.sqrMagnitude < 1e-4f) return 0f;
|
||||
return Mathf.Clamp(Vector3.SignedAngle(Vector3.forward, flat, Vector3.up), -150f, 150f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A hood over the end that meets a machine: an arch of iron hoops with a skin over them, open toward the belt, closed
|
||||
/// against the machine. <paramref name="way"/> is +1 when the hood runs on from the start, -1 back from the end.
|
||||
/// </summary>
|
||||
void Hood(float z, float way)
|
||||
{
|
||||
const int Arc = 7;
|
||||
const float R = 0.5f, Long = 0.55f;
|
||||
for (int hoop = 0; hoop <= 2; hoop++)
|
||||
{
|
||||
float hz = z + way * Long * hoop / 2f;
|
||||
for (int k = 0; k < Arc; k++)
|
||||
{
|
||||
float a0 = Mathf.PI * k / Arc, a1 = Mathf.PI * (k + 1) / Arc;
|
||||
var p0 = new Vector3(Mathf.Cos(a0) * R, Mathf.Sin(a0) * R * 0.7f, hz);
|
||||
var p1 = new Vector3(Mathf.Cos(a1) * R, Mathf.Sin(a1) * R * 0.7f, hz);
|
||||
var d = p1 - p0;
|
||||
Box((p0 + p1) * 0.5f, Quaternion.LookRotation(Vector3.forward, Vector3.Cross(d, Vector3.forward)), new Vector3(d.magnitude + 0.01f, 0.04f, 0.05f));
|
||||
}
|
||||
}
|
||||
// the skin between the first and last hoop
|
||||
for (int k = 0; k < Arc; k++)
|
||||
{
|
||||
float a0 = Mathf.PI * k / Arc, a1 = Mathf.PI * (k + 1) / Arc;
|
||||
Vector3 P(float a, float zz) => new Vector3(Mathf.Cos(a) * (R - 0.02f), Mathf.Sin(a) * (R - 0.02f) * 0.7f, zz);
|
||||
var n = new Vector3(Mathf.Cos((a0 + a1) * 0.5f), Mathf.Sin((a0 + a1) * 0.5f), 0f);
|
||||
float z0 = z, z1 = z + way * Long;
|
||||
if (way > 0f) Quad(P(a0, z0), P(a1, z0), P(a1, z1), P(a0, z1), n, Vector2.zero, Vector2.one);
|
||||
else Quad(P(a1, z0), P(a0, z0), P(a0, z1), P(a1, z1), n, Vector2.zero, Vector2.one);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Two legs spread apart straight down from the bed to whatever is underneath, a low block if there's hardly any room.</summary>
|
||||
void Post(Vector3 a, Quaternion rot, Vector3 on, Vector3 fwd)
|
||||
{
|
||||
var top = a + rot * on;
|
||||
var up = Planet.Up(top);
|
||||
float drop = Planet.Altitude(top);
|
||||
const int Under = (1 << Layers.Default) | (1 << Layers.Build);
|
||||
if (Physics.Raycast(top - up * 0.2f, -up, out var hit, Mathf.Max(0.1f, drop), Under, QueryTriggerInteraction.Ignore)) drop = hit.distance + 0.2f;
|
||||
if (drop < 0.2f) return;
|
||||
var down = Quaternion.Inverse(rot) * -up;
|
||||
// square across the belt where it stands, leaning with the ground
|
||||
var stand = Quaternion.FromToRotation(Vector3.down, down) * Quaternion.LookRotation(fwd, Vector3.up);
|
||||
var at = on;
|
||||
float reach = drop;
|
||||
if (reach < 0.5f)
|
||||
{
|
||||
Box(at + down * reach * 0.5f, stand, new Vector3(0.7f, reach, 0.14f));
|
||||
return;
|
||||
}
|
||||
foreach (float side in new[] { -1f, 1f })
|
||||
{
|
||||
var from = at + stand * Vector3.right * side * 0.34f;
|
||||
var to = at + down * reach + stand * Vector3.right * side * 0.5f;
|
||||
Box((from + to) * 0.5f, Quaternion.FromToRotation(Vector3.up, from - to), new Vector3(0.11f, (from - to).magnitude, 0.11f));
|
||||
Box(to, stand, new Vector3(0.26f, 0.05f, 0.36f));
|
||||
}
|
||||
Box(at + down * reach * 0.55f, stand, new Vector3(0.84f, 0.07f, 0.06f));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Materials for what's generated at run time.</summary>
|
||||
public static class BuildLook
|
||||
{
|
||||
public static Material Mat(string name, Color fallback)
|
||||
{
|
||||
var m = AssetBank.I ? AssetBank.I.Mat(name) : null;
|
||||
return m ? m : new Material(Shader.Find("Universal Render Pipeline/Lit")) { color = fallback };
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BeltRun.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BeltRun.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c57a0b3c248f700448b75d76321f7695
|
||||
123
Assets/Scripts/Gameplay/BeltSplitter.cs
Normal file
123
Assets/Scripts/Gameplay/BeltSplitter.cs
Normal file
@ -0,0 +1,123 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A belt comes in at the back and every bundle picks its way in the middle: right, left or straight on, only ways that
|
||||
/// have something joined to them, and never one that's full, so one blocked belt doesn't hold up the others. E turns it into
|
||||
/// a sorter: one kind of cargo goes left and the rest go the other ways. The flap swings toward the way a bundle is taking.
|
||||
/// </summary>
|
||||
public class BeltSplitter : Conveyor, IJunction
|
||||
{
|
||||
const float Middle = 0.5f;
|
||||
|
||||
public Transform paddle;
|
||||
int _next;
|
||||
float _paddleAngle, _paddleTarget;
|
||||
Quaternion _paddleRest;
|
||||
Cargo _lastSeen;
|
||||
|
||||
protected override void Start()
|
||||
{
|
||||
base.Start();
|
||||
if (paddle) _paddleRest = paddle.localRotation;
|
||||
}
|
||||
|
||||
public const int Overflow = 4;
|
||||
public int ModeCount => 5;
|
||||
public string ModeName(int mode) => mode == 0 ? Loc.T("deals bundles out in turn") : mode == Overflow ? Loc.T("straight on, to the sides only when that's full") : (CargoKind)(mode - 1) == CargoKind.Grass ? Loc.T("Grass goes left, the rest the other ways") : (CargoKind)(mode - 1) == CargoKind.Hay ? Loc.T("Hay goes left, the rest the other ways") : Loc.T("Brick goes left, the rest the other ways");
|
||||
public Color ModeColor(int mode) => mode == 1 ? new Color(0.35f, 0.8f, 0.25f) : mode == 2 ? new Color(0.95f, 0.75f, 0.2f) : mode == 3 ? new Color(0.75f, 0.3f, 0.15f) : mode == Overflow ? new Color(0.25f, 0.7f, 0.95f) : Color.white;
|
||||
|
||||
// route 0 = out to the right, route 1 = out to the left, route 2 = straight on
|
||||
const int Left = 1;
|
||||
protected override int RouteCount => 3;
|
||||
protected override float Turn => Middle;
|
||||
static float Side(int route) => route == 0 ? 1f : route == Left ? -1f : 0f;
|
||||
|
||||
protected override Vector2 PathAt(float d, int route) =>
|
||||
d < Middle || route == 2 ? new Vector2(0f, d - Middle) : new Vector2(Side(route) * (d - Middle), 0f);
|
||||
|
||||
protected override int EntryRoute(Cargo c, int port) => 2;
|
||||
|
||||
protected override int RouteAt(Vector2 local, Cargo c) => local.y > -0.1f && Mathf.Abs(local.x) > 0.1f ? (local.x > 0f ? 0 : Left) : 2;
|
||||
|
||||
/// <summary>Bundles on different ways don't queue behind each other once they're past the middle.</summary>
|
||||
protected override bool Apart(Slot ahead, Slot s) => ahead.set && (s.set ? ahead.route != s.route : ahead.d > Middle + 0.1f);
|
||||
|
||||
bool Free(int route)
|
||||
{
|
||||
if (!ExitOpen(route)) return false;
|
||||
foreach (var o in Items) if (o.set && o.route == route && o.d < Middle + Spacing) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Send(Slot s, int route)
|
||||
{
|
||||
if (!Free(route)) return false;
|
||||
s.route = route;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override bool Choose(Slot s)
|
||||
{
|
||||
int mode = Mode;
|
||||
if (mode == Overflow)
|
||||
{
|
||||
// straight on first; only a full or missing way ahead spills to the sides
|
||||
if (Connected(2) && Free(2)) { s.route = 2; return true; }
|
||||
for (int k = 0; k < 2; k++)
|
||||
{
|
||||
int r = (_next + k) % 2;
|
||||
if (Connected(r) && Free(r)) { _next = (r + 1) % 2; s.route = r; return true; }
|
||||
}
|
||||
return !Connected(0) && !Connected(Left) && !Connected(2) && Send(s, 2);
|
||||
}
|
||||
if (mode > 0 && (int)s.c.kind == mode - 1) return Send(s, Left);
|
||||
bool joined = false;
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
int r = (_next + k) % 3;
|
||||
if (mode > 0 && r == Left) continue;
|
||||
if (!Connected(r)) continue;
|
||||
joined = true;
|
||||
if (!Free(r)) continue;
|
||||
_next = (r + 1) % 3;
|
||||
s.route = r;
|
||||
return true;
|
||||
}
|
||||
// nothing to send it down: it waits if something is joined, and falls off the end if nothing is
|
||||
return !joined && Send(s, mode > 0 ? 0 : 2);
|
||||
}
|
||||
|
||||
protected override void Update()
|
||||
{
|
||||
base.Update();
|
||||
// every peer: watch the junction and swing the flap toward the item crossing it
|
||||
bool seen = false;
|
||||
Cargo inJunction = null;
|
||||
float side = 0f;
|
||||
foreach (var c in Cargo.All)
|
||||
{
|
||||
if (!c) continue;
|
||||
var l = transform.InverseTransformPoint(c.transform.position);
|
||||
if (Mathf.Abs(l.x) > 0.55f || Mathf.Abs(l.z) > 0.55f || l.y < -0.2f || l.y > 1.4f) continue;
|
||||
if (l.z < -0.2f) continue;
|
||||
inJunction = c;
|
||||
side = Mathf.Abs(l.x) > 0.08f ? Mathf.Sign(l.x) : 0f;
|
||||
seen = Mathf.Abs(l.x) > 0.08f || l.z > 0.08f;
|
||||
if (seen) break;
|
||||
}
|
||||
if (seen && inJunction != _lastSeen)
|
||||
{
|
||||
_lastSeen = inJunction;
|
||||
_paddleTarget = -side * 38f;
|
||||
Sfx.PlayAt("splitter_flip", transform.position + transform.up * 0.4f, 0.55f, 1f, 0.08f);
|
||||
}
|
||||
if (paddle)
|
||||
{
|
||||
_paddleAngle = Mathf.MoveTowards(_paddleAngle, _paddleTarget, Time.deltaTime * 260f);
|
||||
paddle.localRotation = Quaternion.AngleAxis(_paddleAngle, paddle.parent ? paddle.parent.InverseTransformDirection(transform.up) : Vector3.up) * _paddleRest;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BeltSplitter.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BeltSplitter.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b489ca288de487148a6ee9dbffafc403
|
||||
19
Assets/Scripts/Gameplay/Binder.cs
Normal file
19
Assets/Scripts/Gameplay/Binder.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>E hands it what's in your tool; it ties that into bundles and sends them down the belt.</summary>
|
||||
public class Binder : SiloPiece
|
||||
{
|
||||
public override string Prompt => Silo.Value >= 1f ? Loc.F("Binder: hand in your grass ({0} still to tie)", GameDefs.Kilos(Silo.Value)) : Loc.T("Binder: hand in your grass");
|
||||
public override bool CanInteract => PlayerAgent.Local && PlayerAgent.Local.Tank.Value >= 0.005f;
|
||||
|
||||
public override void Interact() => PlayerAgent.Local?.Tools.Feed(this);
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Binder.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Binder.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dd2332c594051834ea5b9c29aa0a8f3d
|
||||
255
Assets/Scripts/Gameplay/BuildPiece.cs
Normal file
255
Assets/Scripts/Gameplay/BuildPiece.cs
Normal file
@ -0,0 +1,255 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A placed machine, belt or foundation. It stands wherever it was put on the ball; spawned, moved and removed by the server.</summary>
|
||||
public class BuildPiece : NetworkBehaviour
|
||||
{
|
||||
public static readonly List<BuildPiece> All = new List<BuildPiece>();
|
||||
public static event System.Action PiecesChanged;
|
||||
/// <summary>Goes up whenever something is built, moved or removed: belts look up their links again.</summary>
|
||||
public static int Version { get; private set; }
|
||||
|
||||
public PieceId piece;
|
||||
/// <summary>Belts: where the run ends. It starts at the piece's own position.</summary>
|
||||
public readonly NetworkVariable<Vector3> To = new NetworkVariable<Vector3>();
|
||||
/// <summary>Starter kit: removing it refunds nothing.</summary>
|
||||
public readonly NetworkVariable<bool> Free = new NetworkVariable<bool>();
|
||||
/// <summary>The mode E switches a junction to, saved with the build. 0 if it has none.</summary>
|
||||
public readonly NetworkVariable<int> Mode = new NetworkVariable<int>();
|
||||
/// <summary>Upgrade level, 0 (Mk I) to <see cref="GameDefs.MaxTier"/>.</summary>
|
||||
public readonly NetworkVariable<byte> Tier = new NetworkVariable<byte>();
|
||||
/// <summary>The on/off switch some pieces have: a belt stopped, a machine paused.</summary>
|
||||
public readonly NetworkVariable<byte> Opt = new NetworkVariable<byte>();
|
||||
|
||||
BeltRun _run;
|
||||
IPorts _ports;
|
||||
|
||||
public PieceDef Def => GameDefs.Piece(piece);
|
||||
/// <summary>Stays where it was put: belts lie on top of the grass, a Reaper leaves.</summary>
|
||||
bool Stands => !_run && !GetComponent<Reaper>();
|
||||
public BeltRun Run => _run;
|
||||
|
||||
/// <summary>What it cost, which is what comes back when it's removed.</summary>
|
||||
public double Price => _run ? GameDefs.BeltPrice(_run.Metres) : Def.price;
|
||||
|
||||
/// <summary>Mode, tier and option in one int for the save: the low byte is the mode, as saves from before tiers had it.</summary>
|
||||
public int Setting
|
||||
{
|
||||
get => (Mode.Value & 0xFF) | (Tier.Value << 8) | (Opt.Value << 16);
|
||||
set
|
||||
{
|
||||
Mode.Value = value & 0xFF;
|
||||
Tier.Value = (byte)Mathf.Clamp((value >> 8) & 0xFF, 0, GameDefs.MaxTier);
|
||||
Opt.Value = (byte)((value >> 16) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
public UpgradeKind Upgrades => GameDefs.UpgradeOf(piece);
|
||||
/// <summary>What the tier does to this piece's pace: belts' speed, machines' work, robots' speed and hopper, silos' output.</summary>
|
||||
public float TierMul => GameDefs.TierMul(Upgrades, Tier.Value);
|
||||
public bool Switched => Opt.Value != 0;
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void UpgradeRpc(RpcParams rpc = default)
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
if (!ts || Upgrades == UpgradeKind.None || Tier.Value >= GameDefs.MaxTier) return;
|
||||
double price = GameDefs.UpgradePrice(this, Tier.Value);
|
||||
if (ts.Money.Value < price) { ts.DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
||||
ts.Money.Value -= price;
|
||||
Tier.Value++;
|
||||
UpgradedRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void UpgradedRpc()
|
||||
{
|
||||
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("perk_unlock", transform.position, 0.8f);
|
||||
Tween.Scale(transform, new Vector3(1.12f, 0.85f, 1.12f), Vector3.one, 0.35f, Ease.OutBack, 0f, null);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void SwitchRpc() => Opt.Value = (byte)(Opt.Value == 0 ? 1 : 0);
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void NextModeRpc(int count)
|
||||
{
|
||||
if (count > 0) Mode.Value = (Mode.Value + 1) % count;
|
||||
}
|
||||
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
if (_ports == null) _ports = GetComponentInChildren<IPorts>();
|
||||
_ports?.Ports(into);
|
||||
}
|
||||
|
||||
/// <summary>The grass was laid out afresh (the ball changed size): this piece keeps it off its spot again.</summary>
|
||||
public void Reblock()
|
||||
{
|
||||
if (Stands && Planet.Altitude(transform.position) < 1f) MowMap.BlockRound(transform.position, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
|
||||
}
|
||||
|
||||
/// <summary>Everything looks at its neighbours again (belts fit their ends anew).</summary>
|
||||
public static void Moved() => Version++;
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
_run = GetComponentInChildren<BeltRun>();
|
||||
if (_run) _run.Lay(transform.position, To.Value);
|
||||
// grass doesn't grow through a machine
|
||||
if (Stands && Planet.Altitude(transform.position) < 1f) MowMap.BlockRound(transform.position, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
|
||||
if (transform.childCount > 0 && Time.timeSinceLevelLoad > 3f)
|
||||
{
|
||||
// ports read while it bounced were off, so everything looks again once it has settled
|
||||
Tween.Scale(transform, new Vector3(1.2f, 0.4f, 1.2f), Vector3.one, 0.4f, Ease.OutBack, 0f, Touched);
|
||||
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("build_place", transform.position, 0.9f);
|
||||
}
|
||||
Touched();
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("build_remove", transform.position, 0.9f);
|
||||
Touched();
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
public void MovedRpc(Vector3 at, Quaternion rot)
|
||||
{
|
||||
transform.SetPositionAndRotation(at, rot);
|
||||
var bot = GetComponent<Mowbot>();
|
||||
if (bot) bot.Moved(at);
|
||||
if (Stands && Planet.Altitude(at) < 1f) MowMap.BlockRound(at, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
|
||||
Fx.Build(at, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("build_place", at, 0.9f);
|
||||
Touched();
|
||||
}
|
||||
|
||||
static void Touched()
|
||||
{
|
||||
Version++;
|
||||
PiecesChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What may stand where, shared by the ghost in the player's hands and the server.</summary>
|
||||
public static class BuildRules
|
||||
{
|
||||
/// <summary>The console's `freebuild` and the test bots: standing grass stops nothing.</summary>
|
||||
public static bool AnyGround;
|
||||
public static string Uncut => Loc.T("Mow the grass here first");
|
||||
// spots under a piece that must be cut, of the 25 looked at: a stray tuft doesn't count
|
||||
const int Enough = 23;
|
||||
|
||||
static readonly Collider[] s_hits = new Collider[16];
|
||||
static readonly List<BuildPiece> s_riders = new List<BuildPiece>();
|
||||
|
||||
/// <summary>Can something start from here, on cut ground?</summary>
|
||||
public static bool CutUnder(Vector3 p) => AnyGround || MowMap.Clear(p);
|
||||
|
||||
public static Quaternion RunRotation(Vector3 a, Vector3 b) => Quaternion.LookRotation(b - a, Planet.Up((a + b) * 0.5f));
|
||||
|
||||
/// <summary>Pieces standing on a foundation: they go along when it moves and keep it from being removed. Belts stay where they are.</summary>
|
||||
public static List<BuildPiece> Riders(BuildPiece foundation)
|
||||
{
|
||||
s_riders.Clear();
|
||||
var t = foundation.transform;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || p == foundation || p.Run || GameDefs.IsFoundation(p.piece)) continue;
|
||||
// the position, not the bouncing scale: a piece just put down is still squashed
|
||||
var l = Quaternion.Inverse(t.rotation) * (p.transform.position - t.position);
|
||||
if (Mathf.Abs(l.x) < 2f && Mathf.Abs(l.z) < 2f && Mathf.Abs(l.y - Foundation.TopOf(foundation.piece)) < 0.4f) s_riders.Add(p);
|
||||
}
|
||||
return s_riders;
|
||||
}
|
||||
|
||||
static bool Reserved(Vector3 p)
|
||||
{
|
||||
foreach (var b in GridBlocker.All) if (b.Covers(p)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool Clear(Vector3 center, Vector3 half, Quaternion rot, BuildPiece moving, out string reason)
|
||||
{
|
||||
const int Mask = (1 << Layers.Default) | (1 << Layers.Vehicle) | (1 << Layers.Build);
|
||||
int n = Physics.OverlapBoxNonAlloc(center, half, s_hits, rot, Mask, QueryTriggerInteraction.Ignore);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (s_hits[i].GetComponentInParent<DeckTileView>()) continue;
|
||||
var p = s_hits[i].GetComponentInParent<BuildPiece>();
|
||||
if (moving && p && (p == moving || Riders(moving).Contains(p))) continue;
|
||||
reason = p ? Loc.F("{0} is in the way", p.Def.name) : s_hits[i].GetComponentInParent<Vehicle>() ? Loc.T("A machine is parked here") : Loc.T("Something is in the way");
|
||||
return false;
|
||||
}
|
||||
reason = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Can a piece stand here? A piece being moved doesn't get in its own way.</summary>
|
||||
public static bool CanPlace(PieceDef d, Vector3 at, Quaternion rot, BuildPiece moving, out string reason)
|
||||
{
|
||||
float hx = d.sizeX * 0.5f, hz = d.sizeZ * 0.5f;
|
||||
var r = rot * Vector3.right * hx;
|
||||
var f = rot * Vector3.forward * hz;
|
||||
if (Reserved(at) || Reserved(at + r + f) || Reserved(at + r - f) || Reserved(at - r + f) || Reserved(at - r - f))
|
||||
{
|
||||
reason = Loc.T("That's where a base building stands");
|
||||
return false;
|
||||
}
|
||||
bool slab = GameDefs.IsFoundation(d.id);
|
||||
// a hair more than half a wall's thickness: what fills a room (stairs end to end) may touch its walls
|
||||
var half = new Vector3(hx - (slab ? 0.3f : 0.12f), slab ? 0.2f : 0.6f, hz - (slab ? 0.3f : 0.12f));
|
||||
if (GameDefs.FitOf(d.id) == Fit.Edge) half = new Vector3(hx - 0.2f, 0.6f, 0.05f);
|
||||
if (!Clear(at + rot * Vector3.up * (half.y + 0.12f), half, rot, moving, out reason)) return false;
|
||||
// what stands on a foundation stands on what's under the foundation
|
||||
if (AnyGround || Planet.Altitude(at) > 0.2f) return true;
|
||||
int cut = 0;
|
||||
for (int x = -2; x <= 2; x++)
|
||||
for (int z = -2; z <= 2; z++)
|
||||
if (MowMap.Clear(at + r * x * 0.45f + f * z * 0.45f)) cut++;
|
||||
if (cut >= Enough) return true;
|
||||
reason = Loc.F("Mow the grass here first: {0}% cut", cut * 4);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Can a belt run from A to B?</summary>
|
||||
public static bool CanRun(Vector3 a, Vector3 b, out string reason)
|
||||
{
|
||||
float len = Vector3.Distance(a, b);
|
||||
if (len < GameDefs.BeltShortest) { reason = Loc.T("Too short"); return false; }
|
||||
if (len > GameDefs.BeltLongest) { reason = Loc.F("Too long: belts are up to {0:0} m", GameDefs.BeltLongest); return false; }
|
||||
var dir = (b - a) / len;
|
||||
var up = Planet.Up((a + b) * 0.5f);
|
||||
if (Mathf.Abs(Vector3.Dot(dir, up)) > Mathf.Sin(GameDefs.BeltSteepest * Mathf.Deg2Rad)) { reason = Loc.T("Too steep"); return false; }
|
||||
if (BeltNet.Taken(b)) { reason = Loc.T("A belt already ends here"); return false; }
|
||||
int spots = 0, uncut = 0;
|
||||
for (float z = 0f; z <= len; z += 1f)
|
||||
{
|
||||
var p = a + dir * z;
|
||||
if (Reserved(p)) { reason = Loc.T("That's where a base building stands"); return false; }
|
||||
if (Planet.Altitude(p) < 0.05f) { reason = Loc.T("The ground is in the way"); return false; }
|
||||
spots++;
|
||||
if (!MowMap.Clear(p)) uncut++;
|
||||
}
|
||||
if (!AnyGround && uncut * 6 > spots) { reason = Loc.T("Mow a path for the belt first"); return false; }
|
||||
if (len < 1.3f) { reason = null; return true; }
|
||||
// the ends may touch what they're joined to
|
||||
return Clear((a + b) * 0.5f, new Vector3(0.42f, 0.2f, len * 0.5f - 0.6f), RunRotation(a, b), null, out reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BuildPiece.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BuildPiece.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b8baa8ad05bf317418f3c510defc8b7e
|
||||
95
Assets/Scripts/Gameplay/Cargo.cs
Normal file
95
Assets/Scripts/Gameplay/Cargo.cs
Normal file
@ -0,0 +1,95 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A shippable item: grass bundle, hay or pressed brick. Physics + Grabbable carry it around; when it tumbles off the
|
||||
/// deck it lands in the meadow with a puff of clippings. A depot takes it the moment it drops in.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(Grabbable))]
|
||||
public class Cargo : NetworkBehaviour
|
||||
{
|
||||
public static readonly List<Cargo> All = new List<Cargo>();
|
||||
|
||||
public CargoKind kind;
|
||||
/// <summary>Half height (ground contact checks).</summary>
|
||||
public float halfHeight = 0.33f;
|
||||
public readonly NetworkVariable<float> Kg = new NetworkVariable<float>(GameDefs.BundleKg);
|
||||
|
||||
Grabbable _g;
|
||||
bool _wasInGrass;
|
||||
public bool Loaded { get; set; }
|
||||
/// <summary>Server: the belt this item is locked onto (null when loose).</summary>
|
||||
public Conveyor Belt { get; set; }
|
||||
public Grabbable Grab => _g ? _g : (_g = GetComponent<Grabbable>());
|
||||
|
||||
void Awake() { _g = GetComponent<Grabbable>(); }
|
||||
|
||||
/// <summary>Server: unlock from the belt and become a loose physics body again.</summary>
|
||||
public void ServerLeaveBelt(Vector3 velocity)
|
||||
{
|
||||
if (Belt) Belt.ServerRemove(this, velocity);
|
||||
}
|
||||
|
||||
/// <summary>E at the depot or a machine with this bundle in your arms.</summary>
|
||||
[Rpc(SendTo.Server)]
|
||||
public void HandInRpc(ulong piece, RpcParams rpc = default)
|
||||
{
|
||||
if (Grab.Holder.Value != rpc.Receive.SenderClientId || Grab.Consumed) return;
|
||||
if (!NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(piece, out var no)) return;
|
||||
var sink = no.GetComponentInChildren<ICargoSink>();
|
||||
if (sink == null || (transform.position - no.transform.position).sqrMagnitude > 49f) return;
|
||||
Grab.ServerForceRelease();
|
||||
sink.ServerAccept(this, transform.position, Vector3.down);
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
if (Time.timeSinceLevelLoad > 3f) Tween.Scale(transform, Vector3.one * 0.3f, Vector3.one, 0.35f, Ease.OutBack);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
if (Belt) { Belt.ServerRemove(this, Vector3.zero); Belt = null; }
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
float _fallV;
|
||||
|
||||
void FixedUpdate()
|
||||
{
|
||||
if (!IsSpawned) return;
|
||||
var rb = _g.Body;
|
||||
var p = transform.position;
|
||||
|
||||
// tossed into a depot
|
||||
if (IsServer && !_g.IsHeld && !_g.Consumed && !Belt)
|
||||
foreach (var d in Depot.All)
|
||||
if (d && (p - d.Mouth).sqrMagnitude < 1.1f) { d.ServerAccept(this, p, Vector3.down); return; }
|
||||
|
||||
var up = Planet.Up(p);
|
||||
bool inGrass = Planet.Altitude(p) - halfHeight < 0.25f;
|
||||
// thump into the meadow: a puff of clippings
|
||||
if (inGrass && !_wasInGrass && _fallV < -2.5f)
|
||||
{
|
||||
Fx.Splash(Planet.Surface(p), Mathf.Clamp01(-_fallV / 10f) + 0.3f);
|
||||
Sfx.PlayAt(_fallV < -6f ? "splash_big" : "splash_small", p, 0.8f, 1.1f, 0.1f);
|
||||
}
|
||||
_wasInGrass = inGrass;
|
||||
_fallV = rb.isKinematic ? 0f : Vector3.Dot(rb.linearVelocity, up);
|
||||
if (!IsOwner || rb.isKinematic || _g.IsHeld || !inGrass) return;
|
||||
// the thick grass brakes rolling cargo
|
||||
rb.AddForce(-Vector3.ProjectOnPlane(rb.linearVelocity, up) * 2.2f, ForceMode.Acceleration);
|
||||
rb.angularVelocity *= 0.96f;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Cargo.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Cargo.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 674efdadb118e3e45bd8298e372b4789
|
||||
50
Assets/Scripts/Gameplay/Catcher.cs
Normal file
50
Assets/Scripts/Gameplay/Catcher.cs
Normal file
@ -0,0 +1,50 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Catches what a Reaper shoots from anywhere on the planet and puts it on the belt.</summary>
|
||||
public class Catcher : SiloPiece
|
||||
{
|
||||
const float Room = 100f;
|
||||
|
||||
static readonly List<Catcher> s_all = new List<Catcher>();
|
||||
|
||||
public override string Prompt => Loc.F("Bundle Catcher: {0} of {1}", GameDefs.Kilos(Silo.Value), GameDefs.Kilos(Room));
|
||||
|
||||
public override void Interact() => Sfx.Play("ui_click", 0.6f);
|
||||
|
||||
public override void OnNetworkSpawn() => s_all.Add(this);
|
||||
public override void OnNetworkDespawn() => s_all.Remove(this);
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
s_all.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
|
||||
/// <summary>The emptiest catcher that still has room.</summary>
|
||||
public static Catcher WithRoom()
|
||||
{
|
||||
Catcher best = null;
|
||||
foreach (var c in s_all)
|
||||
if (c && c.Silo.Value + GameDefs.BundleKg <= Room && (!best || c.Silo.Value < best.Silo.Value)) best = c;
|
||||
return best;
|
||||
}
|
||||
|
||||
public void ServerCatch(float kg)
|
||||
{
|
||||
Silo.Value += kg;
|
||||
CaughtRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void CaughtRpc() => Sfx.PlayAt("cargo_load", transform.position, 0.5f, 1f, 0.1f, 0.4f);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Catcher.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Catcher.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bd7c57c2d64397347bdd44709fca3a70
|
||||
536
Assets/Scripts/Gameplay/Conveyor.cs
Normal file
536
Assets/Scripts/Gameplay/Conveyor.cs
Normal file
@ -0,0 +1,536 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Where cargo enters or leaves a piece, in world space.</summary>
|
||||
public struct Port
|
||||
{
|
||||
public Vector3 at, dir;
|
||||
public bool input;
|
||||
}
|
||||
|
||||
/// <summary>Anything with ports a belt can be joined to.</summary>
|
||||
public interface IPorts
|
||||
{
|
||||
void Ports(List<Port> into);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A belt with a real queue. Cargo that lands on it locks onto the centre line (server-owned, kinematic) and rides along
|
||||
/// a fixed path at belt speed, keeping <see cref="Spacing"/> to the item ahead. At the end it is handed to whatever stands
|
||||
/// at the exit: the next belt, a machine's port, a belt it runs into from the side, or dropped off onto the ground. If
|
||||
/// none of those can take it right now it simply waits at the end and the line behind it queues up. No piles, no jams.
|
||||
/// </summary>
|
||||
public class Conveyor : MonoBehaviour, IPorts
|
||||
{
|
||||
public float speed = 1.6f;
|
||||
/// <summary>Built belts follow the team's Fast Belts perk instead of a fixed speed.</summary>
|
||||
public bool usePerkSpeed;
|
||||
/// <summary>Belt texture repeats per metre of belt (matches the material's V tiling).</summary>
|
||||
public float uvPerMetre = 2f;
|
||||
public Renderer[] belts;
|
||||
|
||||
/// <summary>Gap between item centres along the belt.</summary>
|
||||
public const float Spacing = 0.58f;
|
||||
/// <summary>Height of a junction's surface above what it stands on.</summary>
|
||||
public const float Top = 0.35f;
|
||||
|
||||
protected class Slot
|
||||
{
|
||||
public Cargo c;
|
||||
public float d;
|
||||
public int route;
|
||||
public Vector3 from;
|
||||
public float blend;
|
||||
/// <summary>Has it settled which way it's going?</summary>
|
||||
public bool set;
|
||||
}
|
||||
|
||||
struct Link
|
||||
{
|
||||
public Conveyor belt;
|
||||
public int port;
|
||||
public bool side;
|
||||
public float at;
|
||||
public ICargoSink sink;
|
||||
}
|
||||
|
||||
public static readonly List<Conveyor> All = new List<Conveyor>();
|
||||
|
||||
/// <summary>Front of the belt first (largest d).</summary>
|
||||
protected readonly List<Slot> Items = new List<Slot>();
|
||||
MaterialPropertyBlock _mpb;
|
||||
float _offset;
|
||||
BuildPiece _piece;
|
||||
Link[] _links;
|
||||
int _found, _linkVersion = -1;
|
||||
static readonly int BaseMapST = Shader.PropertyToID("_BaseMap_ST");
|
||||
static readonly List<Port> s_out = new List<Port>();
|
||||
static readonly Collider[] s_hits = new Collider[8];
|
||||
|
||||
public float Speed => Piece && Piece.Switched ? 0f : (usePerkSpeed && TeamState.Instance ? GameDefs.BeltSpeed : speed) * (Piece ? Piece.TierMul : 1f);
|
||||
public BuildPiece Piece => _piece ? _piece : (_piece = GetComponentInParent<BuildPiece>());
|
||||
public int Count => Items.Count;
|
||||
protected int Mode => Piece ? Piece.Mode.Value : 0;
|
||||
/// <summary>Could something come in through a port right now?</summary>
|
||||
public bool HasRoom => MinD >= Spacing;
|
||||
protected static bool Server => NetworkManager.Singleton && NetworkManager.Singleton.IsServer;
|
||||
|
||||
protected virtual void Start() { _mpb = new MaterialPropertyBlock(); }
|
||||
void OnEnable() { All.Add(this); }
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
All.Remove(this);
|
||||
// the piece is going away: whatever rides on it falls off where it is
|
||||
if (Server) for (int i = Items.Count - 1; i >= 0; i--) Release(Items[i], transform.up * 0.5f);
|
||||
Items.Clear();
|
||||
}
|
||||
|
||||
protected virtual void Update()
|
||||
{
|
||||
if (belts == null || belts.Length == 0 || _mpb == null) return;
|
||||
// belt meshes carry V in metres and run +V along the flow
|
||||
_offset = Mathf.Repeat(_offset - Speed * Time.deltaTime * uvPerMetre, 1f);
|
||||
foreach (var b in belts)
|
||||
{
|
||||
if (!b) continue;
|
||||
b.GetPropertyBlock(_mpb);
|
||||
_mpb.SetVector(BaseMapST, new Vector4(1, uvPerMetre, 0, _offset));
|
||||
b.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── path (local XZ, +Z = flow) ─────────────────────────
|
||||
|
||||
protected virtual int RouteCount => 1;
|
||||
|
||||
/// <summary>Height of the moving surface in local space.</summary>
|
||||
protected virtual float Surface => Top;
|
||||
|
||||
/// <summary>Does this belt take items from the side?</summary>
|
||||
protected virtual bool Sides => false;
|
||||
|
||||
protected virtual float Length(int route) => 1f;
|
||||
|
||||
/// <summary>Point on the centre line, d metres from where items come in.</summary>
|
||||
protected virtual Vector2 PathAt(float d, int route) => new Vector2(0f, d - 0.5f);
|
||||
|
||||
/// <summary>How far the centre line rises above the piece's own level d metres along (a belt that rounds over a crest).</summary>
|
||||
protected virtual float HeightAt(float d, int route) => 0f;
|
||||
|
||||
/// <summary>Server: route for an item that comes in through a port.</summary>
|
||||
protected virtual int EntryRoute(Cargo c, int port) => 0;
|
||||
|
||||
/// <summary>Server: route for an item dropped onto the belt at a local point.</summary>
|
||||
protected virtual int RouteAt(Vector2 local, Cargo c) => EntryRoute(c, 0);
|
||||
|
||||
/// <summary>Server: is it this port's turn to send something in?</summary>
|
||||
protected virtual bool Takes(int port) => true;
|
||||
|
||||
/// <summary>How far along an item goes before it has to settle on a route.</summary>
|
||||
protected virtual float Turn => 0f;
|
||||
|
||||
/// <summary>Server: an item at the turn settles on a route, or waits there (false).</summary>
|
||||
protected virtual bool Choose(Slot s) => true;
|
||||
|
||||
/// <summary>Items on separate ways don't keep their distance.</summary>
|
||||
protected virtual bool Apart(Slot ahead, Slot s) => false;
|
||||
|
||||
/// <summary>Is anything joined to the end of this route?</summary>
|
||||
protected bool Connected(int route)
|
||||
{
|
||||
var l = LinkOf(route);
|
||||
return l.belt || l.sink != null;
|
||||
}
|
||||
|
||||
/// <summary>The point of the path nearest to somewhere in the world, for the sound.</summary>
|
||||
public Vector3 NearestPoint(Vector3 world)
|
||||
{
|
||||
var p = ToLocal(world);
|
||||
Project(new Vector2(p.x, p.z), out int route, out float d);
|
||||
return WorldOnPath(d, route, 0f);
|
||||
}
|
||||
|
||||
public virtual void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(new Port { at = WorldOnPath(0f, 0, 0f), dir = Tangent(0f, 0), input = true });
|
||||
for (int r = 0; r < RouteCount; r++)
|
||||
{
|
||||
float L = Length(r);
|
||||
into.Add(new Port { at = WorldOnPath(L, r, 0f), dir = Tangent(L, r) });
|
||||
}
|
||||
}
|
||||
|
||||
protected Vector3 WorldOnPath(float d, int route, float lift)
|
||||
{
|
||||
var l = PathAt(d, route);
|
||||
return transform.position + transform.rotation * new Vector3(l.x, Surface + lift + HeightAt(d, route), l.y);
|
||||
}
|
||||
|
||||
/// <summary>Where the other end of a route meets whatever it hands over to.</summary>
|
||||
protected virtual Vector3 ExitAt(int route) => WorldOnPath(Length(route), route, 0f);
|
||||
|
||||
// a piece that has just landed is still bouncing: its scale says nothing about where the path runs
|
||||
Vector3 ToLocal(Vector3 world) => Quaternion.Inverse(transform.rotation) * (world - transform.position);
|
||||
|
||||
protected Vector3 Tangent(float d, int route)
|
||||
{
|
||||
float L = Length(route);
|
||||
float d0 = Mathf.Clamp(d - 0.02f, 0f, L), d1 = Mathf.Clamp(d + 0.02f, 0f, L);
|
||||
var a = PathAt(d0, route);
|
||||
var b = PathAt(d1, route);
|
||||
var t = transform.TransformDirection(new Vector3(b.x - a.x, HeightAt(d1, route) - HeightAt(d0, route), b.y - a.y));
|
||||
return t.sqrMagnitude > 1e-6f ? t.normalized : transform.forward;
|
||||
}
|
||||
|
||||
/// <summary>Nearest point on any route to a local point.</summary>
|
||||
protected virtual void Project(Vector2 local, out int route, out float d)
|
||||
{
|
||||
route = 0; d = 0f;
|
||||
float best = float.MaxValue;
|
||||
for (int r = 0; r < RouteCount; r++)
|
||||
{
|
||||
float L = Length(r);
|
||||
for (int k = 0; k <= 16; k++)
|
||||
{
|
||||
float dd = L * k / 16f;
|
||||
float e = (PathAt(dd, r) - local).sqrMagnitude;
|
||||
if (e < best) { best = e; route = r; d = dd; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool FreeAt(float d)
|
||||
{
|
||||
foreach (var s in Items) if (Mathf.Abs(s.d - d) < Spacing) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
float MinD => Items.Count > 0 ? Items[Items.Count - 1].d : float.MaxValue;
|
||||
|
||||
// ───────────────────────── what stands at the exit ─────────────────────────
|
||||
|
||||
/// <summary>Links are looked up the first time they're needed after anything was built, moved or removed.</summary>
|
||||
Link LinkOf(int route)
|
||||
{
|
||||
if (_links == null) _links = new Link[RouteCount];
|
||||
if (_linkVersion != BuildPiece.Version)
|
||||
{
|
||||
_linkVersion = BuildPiece.Version;
|
||||
_found = 0;
|
||||
}
|
||||
if ((_found >> route & 1) == 0)
|
||||
{
|
||||
_links[route] = Find(route);
|
||||
_found |= 1 << route;
|
||||
}
|
||||
return _links[route];
|
||||
}
|
||||
|
||||
Link Find(int route)
|
||||
{
|
||||
var end = ExitAt(route);
|
||||
if (BeltNet.Nearest(end, true, BeltNet.Joined, Piece, out var piece, out int port, out _))
|
||||
{
|
||||
var conv = piece.GetComponentInChildren<Conveyor>();
|
||||
if (conv) return new Link { belt = conv, port = port };
|
||||
var sink = piece.GetComponentInChildren<ICargoSink>();
|
||||
if (sink != null) return new Link { sink = sink };
|
||||
}
|
||||
foreach (var b in All)
|
||||
{
|
||||
if (b == this || !b.Sides) continue;
|
||||
var l = b.ToLocal(end);
|
||||
if (Mathf.Abs(l.x) < 0.6f && Mathf.Abs(l.y) < 0.6f && l.z > 0.3f && l.z < b.Length(0) - 0.3f) return new Link { belt = b, side = true, at = l.z };
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>Could the exit of this route take an item right now?</summary>
|
||||
protected bool ExitOpen(int route)
|
||||
{
|
||||
var l = LinkOf(route);
|
||||
return !l.belt || (l.side ? l.belt.FreeAt(l.at) : l.belt.MinD >= Spacing);
|
||||
}
|
||||
|
||||
// ───────────────────────── server API ─────────────────────────
|
||||
|
||||
/// <summary>Could an item be put on this belt at a world point right now?</summary>
|
||||
public bool CanInsert(Vector3 world)
|
||||
{
|
||||
var p = ToLocal(world);
|
||||
Project(new Vector2(p.x, p.z), out _, out float d);
|
||||
return FreeAt(d);
|
||||
}
|
||||
|
||||
/// <summary>Server: lock an item onto the belt at the nearest point of its path (false: no room there yet).</summary>
|
||||
public bool ServerTryInsert(Cargo c, Vector3 world)
|
||||
{
|
||||
if (!Server || !c || !c.IsSpawned || c.Belt) return false;
|
||||
var p = ToLocal(world);
|
||||
var local = new Vector2(p.x, p.z);
|
||||
Project(local, out int route, out float d);
|
||||
if (!FreeAt(d)) return false;
|
||||
route = RouteCount > 1 ? RouteAt(local, c) : route;
|
||||
Insert(c, d, route);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Server: accept an item handed over through a port.</summary>
|
||||
public bool ServerAcceptPort(Cargo c, int port)
|
||||
{
|
||||
bool turn = Takes(port);
|
||||
if (!turn || MinD < Spacing) return false;
|
||||
Insert(c, 0f, EntryRoute(c, port));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Server: accept an item from a belt that runs into this one's side.</summary>
|
||||
bool ServerSideLoad(Cargo c, float d)
|
||||
{
|
||||
if (!FreeAt(d)) return false;
|
||||
Insert(c, d, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Insert(Cargo c, float d, int route)
|
||||
{
|
||||
var g = c.Grab;
|
||||
if (c.OwnerClientId != NetworkManager.ServerClientId) c.NetworkObject.ChangeOwnership(NetworkManager.ServerClientId);
|
||||
g.Body.linearVelocity = Vector3.zero;
|
||||
g.Body.isKinematic = true;
|
||||
c.Belt = this;
|
||||
var s = new Slot { c = c, d = d, route = route, from = c.transform.position, blend = 0f, set = d > Turn };
|
||||
int i = 0;
|
||||
while (i < Items.Count && Items[i].d > d) i++;
|
||||
Items.Insert(i, s);
|
||||
}
|
||||
|
||||
/// <summary>Server: take an item off this belt (a player grabbed it, it got despawned).</summary>
|
||||
public void ServerRemove(Cargo c, Vector3 velocity)
|
||||
{
|
||||
for (int i = 0; i < Items.Count; i++)
|
||||
if (Items[i].c == c) { var s = Items[i]; Items.RemoveAt(i); Release(s, velocity); return; }
|
||||
if (c && c.Belt == this) c.Belt = null;
|
||||
}
|
||||
|
||||
void Release(Slot s, Vector3 velocity)
|
||||
{
|
||||
var c = s.c;
|
||||
if (!c) return;
|
||||
if (c.Belt == this) c.Belt = null;
|
||||
if (!c.IsSpawned) return;
|
||||
var rb = c.Grab.Body;
|
||||
rb.isKinematic = false;
|
||||
rb.linearVelocity = velocity;
|
||||
rb.angularVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
// ───────────────────────── simulation (server) ─────────────────────────
|
||||
|
||||
void FixedUpdate()
|
||||
{
|
||||
if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return;
|
||||
float dt = Time.fixedDeltaTime;
|
||||
float step = Speed * dt;
|
||||
for (int i = 0; i < Items.Count; i++)
|
||||
{
|
||||
var s = Items[i];
|
||||
if (!s.c || !s.c.IsSpawned || s.c.Loaded || s.c.Belt != this || s.c.Grab.IsHeld)
|
||||
{
|
||||
Items.RemoveAt(i--);
|
||||
if (s.c && s.c.Belt == this) s.c.Belt = null;
|
||||
continue;
|
||||
}
|
||||
float L = Length(s.route);
|
||||
float limit = Room(i, ref L);
|
||||
if (s.d < limit) s.d = Mathf.Min(s.d + step, limit);
|
||||
if ((i == 0 || RouteCount > 1) && s.d >= L - 1e-4f && HandOff(s))
|
||||
{
|
||||
Items.RemoveAt(i--);
|
||||
continue;
|
||||
}
|
||||
Place(s, dt);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How far an item can go: to the turn until it has chosen, then the end of its route, and never into the one ahead.</summary>
|
||||
float Room(int i, ref float L)
|
||||
{
|
||||
var s = Items[i];
|
||||
float limit = L;
|
||||
if (!s.set)
|
||||
{
|
||||
if (s.d < Turn - 1e-4f || !Choose(s)) limit = Turn;
|
||||
else
|
||||
{
|
||||
s.set = true;
|
||||
L = limit = Length(s.route);
|
||||
}
|
||||
}
|
||||
for (int k = i - 1; k >= 0; k--)
|
||||
{
|
||||
if (Apart(Items[k], s)) continue;
|
||||
return Mathf.Min(limit, Items[k].d - Spacing);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
void Place(Slot s, float dt)
|
||||
{
|
||||
var c = s.c;
|
||||
var rb = c.Grab.Body;
|
||||
var target = WorldOnPath(s.d, s.route, c.halfHeight);
|
||||
s.blend = Mathf.MoveTowards(s.blend, 1f, dt * 6f);
|
||||
var pos = s.blend < 1f ? Vector3.Lerp(s.from, target, Easing.Apply(Ease.OutCubic, s.blend)) : target;
|
||||
// square the item up with the flow
|
||||
var want = Quaternion.LookRotation(Tangent(s.d, s.route), transform.up);
|
||||
var rot = Quaternion.RotateTowards(rb.rotation, want, 540f * dt);
|
||||
rb.MovePosition(pos);
|
||||
rb.MoveRotation(rot);
|
||||
}
|
||||
|
||||
/// <summary>The front item reached the end of its route: pass it on if anything can take it.</summary>
|
||||
bool HandOff(Slot s)
|
||||
{
|
||||
var c = s.c;
|
||||
float L = Length(s.route);
|
||||
var link = LinkOf(s.route);
|
||||
var dir = Tangent(L, s.route);
|
||||
if (link.belt)
|
||||
{
|
||||
c.Belt = null;
|
||||
if (link.side ? link.belt.ServerSideLoad(c, link.at) : link.belt.ServerAcceptPort(c, link.port)) return true;
|
||||
c.Belt = this;
|
||||
return false;
|
||||
}
|
||||
if (link.sink != null)
|
||||
{
|
||||
c.Belt = null;
|
||||
var rb = c.Grab.Body;
|
||||
if (link.sink.ServerAccept(c, WorldOnPath(L, s.route, c.halfHeight), dir)) return true;
|
||||
c.Belt = this;
|
||||
rb.isKinematic = true;
|
||||
return false;
|
||||
}
|
||||
// nothing there: drop it off the end, but only onto a free spot (one item waits there at a time)
|
||||
var land = WorldOnPath(L, s.route, 0f) + dir * 0.45f;
|
||||
int n = Physics.OverlapSphereNonAlloc(land, 0.3f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore);
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var other = s_hits[k].GetComponentInParent<Cargo>();
|
||||
if (other && other != c) return false;
|
||||
}
|
||||
Release(s, dir * Mathf.Max(1.2f, Speed) + transform.up * 0.4f);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ───────────────────────── catching loose cargo ─────────────────────────
|
||||
|
||||
protected void OnTriggerStay(Collider other)
|
||||
{
|
||||
if (!Server) return;
|
||||
var rb = other.attachedRigidbody;
|
||||
if (!rb) return;
|
||||
var c = rb.GetComponent<Cargo>();
|
||||
if (!c || !c.IsSpawned || c.Belt || c.Loaded || c.Grab.IsHeld || c.Grab.Consumed) return;
|
||||
// still flying up from a throw: let it come down first
|
||||
if (Vector3.Dot(rb.linearVelocity, transform.up) > 1.5f) return;
|
||||
if (transform.InverseTransformPoint(c.transform.position).y - c.halfHeight > Surface + 0.8f) return;
|
||||
ServerTryInsert(c, c.transform.position);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A piece that swallows cargo handed to it by a belt or a machine.</summary>
|
||||
public interface ICargoSink
|
||||
{
|
||||
/// <summary>Server: take the item (true) or refuse it for now (false: it waits).</summary>
|
||||
bool ServerAccept(Cargo c, Vector3 from, Vector3 dir);
|
||||
}
|
||||
|
||||
/// <summary>Finding ports among everything that's built.</summary>
|
||||
public static class BeltNet
|
||||
{
|
||||
/// <summary>A belt end this close to a port feeds it. Laying one snaps it exactly, so this only forgives rounding.</summary>
|
||||
public const float Joined = 0.4f;
|
||||
/// <summary>How close to a port you have to aim for a belt to snap onto it.</summary>
|
||||
public const float Snap = 1.2f;
|
||||
|
||||
static readonly List<Port> s_list = new List<Port>();
|
||||
static readonly List<Port> s_out = new List<Port>();
|
||||
static readonly Collider[] s_hits = new Collider[8];
|
||||
|
||||
public static bool Nearest(Vector3 near, bool input, float within, BuildPiece skip, out BuildPiece piece, out int index, out Port port)
|
||||
{
|
||||
piece = null; index = -1; port = default;
|
||||
float best = within * within;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || p == skip || !p.IsSpawned) continue;
|
||||
s_list.Clear();
|
||||
p.Ports(s_list);
|
||||
for (int i = 0; i < s_list.Count; i++)
|
||||
{
|
||||
if (s_list[i].input != input) continue;
|
||||
float d = (s_list[i].at - near).sqrMagnitude;
|
||||
if (d >= best) continue;
|
||||
best = d; piece = p; index = i; port = s_list[i];
|
||||
}
|
||||
}
|
||||
return piece;
|
||||
}
|
||||
|
||||
/// <summary>Server: one kilo leaves a machine through a port, onto the belt there or, with no belt, onto clear ground.</summary>
|
||||
public static bool Send(BuildPiece from, Port way, CargoKind kind)
|
||||
{
|
||||
Conveyor belt = null;
|
||||
int port = 0;
|
||||
if (Nearest(way.at, true, Joined, from, out var next, out int index, out _))
|
||||
{
|
||||
belt = next.GetComponentInChildren<Conveyor>();
|
||||
port = index;
|
||||
if (belt && !belt.HasRoom) return false;
|
||||
}
|
||||
else if (Physics.OverlapSphereNonAlloc(way.at + way.dir * 0.5f, 0.45f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore) > 0) return false;
|
||||
var made = Spawner.Instance.SpawnCargo(kind, way.at + way.dir * 0.2f + from.transform.up * 0.35f, from.transform.rotation, way.dir * 1.6f);
|
||||
if (!made) return false;
|
||||
if (belt) belt.ServerAcceptPort(made, port);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A port at the front of a piece, just clear of its solid box.</summary>
|
||||
public static Port Front(Transform piece)
|
||||
{
|
||||
var box = piece.Find("Solid")?.GetComponent<BoxCollider>();
|
||||
float reach = box ? box.transform.localPosition.z + box.size.z * 0.5f + 0.25f : 1.7f;
|
||||
return new Port { at = piece.position + piece.up * GameDefs.BeltLowest + piece.forward * reach, dir = piece.forward };
|
||||
}
|
||||
|
||||
/// <summary>Server: one kilo out of a silo, through whichever port has room. Ports take turns.</summary>
|
||||
public static bool Drain(BuildPiece from, NetworkVariable<float> silo, ref int turn)
|
||||
{
|
||||
if (silo.Value < 1f) return false;
|
||||
s_out.Clear();
|
||||
from.Ports(s_out);
|
||||
for (int i = 0; i < s_out.Count; i++)
|
||||
{
|
||||
turn = (turn + 1) % s_out.Count;
|
||||
if (s_out[turn].input || !Send(from, s_out[turn], CargoKind.Grass)) continue;
|
||||
silo.Value -= 1f;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Does a belt already end here?</summary>
|
||||
public static bool Taken(Vector3 at)
|
||||
{
|
||||
foreach (var c in Conveyor.All)
|
||||
if (c is BeltRun r && (r.End - at).sqrMagnitude < Joined * Joined) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Conveyor.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Conveyor.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 934f648461a295a448cd209fc420d5b9
|
||||
62
Assets/Scripts/Gameplay/Depot.cs
Normal file
62
Assets/Scripts/Gameplay/Depot.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Where grass leaves for Earth: E empties the tool in your hands at once or takes the bundle in your arms, thrown
|
||||
/// bundles and bundles arriving on a belt are paid for the moment they drop in. The HUD writes out a receipt.
|
||||
/// </summary>
|
||||
public class Depot : MonoBehaviour, IInteractable, ICargoSink, IPorts
|
||||
{
|
||||
public static readonly List<Depot> All = new List<Depot>();
|
||||
|
||||
public Transform mouth;
|
||||
/// <summary>Half the footprint across and along; a base intake has its back to the deck and takes no belt there.</summary>
|
||||
public float halfX = 1.05f, halfZ = 1.05f;
|
||||
public bool backToDeck;
|
||||
public Vector3 Mouth => mouth ? mouth.position : transform.position + Vector3.up * 1.1f;
|
||||
|
||||
void OnEnable() => All.Add(this);
|
||||
void OnDisable() => All.Remove(this);
|
||||
|
||||
/// <summary>Three belts on each side, twelve in all.</summary>
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
for (int side = 0; side < 4; side++)
|
||||
{
|
||||
if (backToDeck && side == 2) continue;
|
||||
var inward = Quaternion.AngleAxis(side * 90f, transform.up) * -transform.forward;
|
||||
var across = Vector3.Cross(transform.up, inward);
|
||||
float reach = side % 2 == 0 ? halfZ : halfX, room = side % 2 == 0 ? halfX : halfZ;
|
||||
float step = Mathf.Min(0.6f, room * 0.45f);
|
||||
for (int k = -1; k <= 1; k++)
|
||||
into.Add(new Port { at = transform.position - inward * reach + across * (k * step) + transform.up * GameDefs.BeltLowest, dir = inward, input = true });
|
||||
}
|
||||
}
|
||||
|
||||
public string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
var p = PlayerAgent.Local;
|
||||
if (!p) return null;
|
||||
return p.Tank.Value < 0.005f ? (backToDeck ? Loc.T("Base Intake — nothing to hand in") : Loc.T("Grass Depot — nothing to hand in")) : Loc.F("Hand in {0}", GameDefs.Kilos(p.Tank.Value));
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanInteract => PlayerAgent.Local && PlayerAgent.Local.Tank.Value >= 0.005f;
|
||||
|
||||
public void Interact() => PlayerAgent.Local?.Tools.Deposit(this);
|
||||
|
||||
public bool ServerAccept(Cargo c, Vector3 from, Vector3 dir)
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
if (!ts || !c || !c.IsSpawned) return false;
|
||||
ts.ServerDeposit(c.Kg.Value, c.kind, Mouth);
|
||||
c.Grab.Consumed = true;
|
||||
c.NetworkObject.Despawn(true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Depot.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Depot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1a9223629109a94428a30bda982066d6
|
||||
293
Assets/Scripts/Gameplay/DronePad.cs
Normal file
293
Assets/Scripts/Gameplay/DronePad.cs
Normal file
@ -0,0 +1,293 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A pad of fetching drones. Bundles of grass lying loose within <see cref="Range"/> of it (thrown down, dropped off the
|
||||
/// end of a belt, flung by a twister) are flown in, one per drone per trip, and go into the pad's silo, which puts them
|
||||
/// on the belts like any other silo. A trip is one synced value per drone (where to, when it left), and every peer flies
|
||||
/// the drone along the same plan from it: up, across, down, grab, up, back, down onto the pad.
|
||||
/// </summary>
|
||||
public class DronePad : SiloPiece
|
||||
{
|
||||
public const float Range = 40f;
|
||||
const float Room = 60f, Cruise = 7f, Climb = 3f, Speed = 6f, Hover = 1.35f, GrabTime = 0.8f, Carry = 1f, Look = 0.5f;
|
||||
const int Most = 4;
|
||||
/// <summary>A drone at rest on the pad.</summary>
|
||||
static readonly Vector4 Parked = new Vector4(0f, 0f, 0f, -1f);
|
||||
/// <summary>Where each drone sits on the pad, in the piece's space (the perch post is at the back left).</summary>
|
||||
static readonly Vector3[] Slots = { new Vector3(0.75f, 0.68f, 0.75f), new Vector3(-0.75f, 0.68f, 0.75f), new Vector3(0.75f, 0.68f, -0.75f), new Vector3(-0.75f, 0.68f, -0.75f) };
|
||||
/// <summary>Bundles some drone is on its way to, so no two go for the same one.</summary>
|
||||
static readonly HashSet<Cargo> s_claimed = new HashSet<Cargo>();
|
||||
|
||||
public Transform drone;
|
||||
|
||||
readonly NetworkVariable<Vector4> _trip0 = new NetworkVariable<Vector4>(Parked), _trip1 = new NetworkVariable<Vector4>(Parked);
|
||||
readonly NetworkVariable<Vector4> _trip2 = new NetworkVariable<Vector4>(Parked), _trip3 = new NetworkVariable<Vector4>(Parked);
|
||||
readonly Transform[] _drones = new Transform[Most];
|
||||
readonly Transform[][] _rotors = new Transform[Most][];
|
||||
readonly AudioSource[] _hum = new AudioSource[Most];
|
||||
readonly Cargo[] _for = new Cargo[Most];
|
||||
readonly bool[] _holding = new bool[Most];
|
||||
float _nextLook;
|
||||
/// <summary>Server: bundles brought in since it was built (for the demo's log).</summary>
|
||||
public int Delivered { get; private set; }
|
||||
BuildPiece _piece;
|
||||
|
||||
BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
NetworkVariable<Vector4> Trip(int i) => i == 0 ? _trip0 : i == 1 ? _trip1 : i == 2 ? _trip2 : _trip3;
|
||||
/// <summary>Two drones at Mk I, one more per upgrade, four at most.</summary>
|
||||
int Count => Mathf.Min(Most, 2 + (Piece ? Piece.Tier.Value : 0));
|
||||
float Fly => Speed * Mathf.Sqrt(Piece ? Piece.TierMul : 1f);
|
||||
double Now => NetworkManager ? NetworkManager.ServerTime.Time : Time.timeAsDouble;
|
||||
|
||||
public override string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
int out_ = 0;
|
||||
for (int i = 0; i < Count; i++) if (Trip(i).Value.w >= 0f) out_++;
|
||||
return Loc.F("Drone Pad: {0} drones, {1} out · {2} of {3}", Count, out_, GameDefs.Kilos(Silo.Value), GameDefs.Kilos(Room));
|
||||
}
|
||||
}
|
||||
|
||||
public override void Interact() => Sfx.Play("ui_click", 0.6f);
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (!drone) return;
|
||||
_drones[0] = drone;
|
||||
for (int i = 1; i < Most; i++) _drones[i] = Instantiate(drone, drone.parent);
|
||||
for (int i = 0; i < Most; i++)
|
||||
{
|
||||
var spin = new List<Transform>();
|
||||
foreach (var t in _drones[i].GetComponentsInChildren<Transform>(true))
|
||||
if (t.name.StartsWith("Rotor")) spin.Add(t);
|
||||
_rotors[i] = spin.ToArray();
|
||||
_hum[i] = Sfx.Loop("drone_loop", _drones[i], 0f);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
// whatever was in the air falls where it is
|
||||
for (int i = 0; i < Most; i++) Let(i);
|
||||
base.OnNetworkDespawn();
|
||||
}
|
||||
|
||||
// ───────────────────────── the flight plan ─────────────────────────
|
||||
|
||||
Vector3 Home(int i) => transform.TransformPoint(Slots[i]);
|
||||
|
||||
static float Ease(float k) => k * k * (3f - 2f * k);
|
||||
|
||||
/// <summary>Where drone i is on its trip right now, which stage it's at (7: back on the pad) and how far through it.</summary>
|
||||
Vector3 Where(int i, Vector4 trip, double now, out int leg, out float k, out Vector3 heading)
|
||||
{
|
||||
var home = Home(i);
|
||||
leg = 7; k = 1f; heading = transform.forward;
|
||||
if (trip.w < 0f) return home;
|
||||
var target = new Vector3(trip.x, trip.y, trip.z);
|
||||
var a = home + Planet.Up(home) * Cruise;
|
||||
var b = target + Planet.Up(target) * Cruise;
|
||||
var low = target + Planet.Up(target) * Hover;
|
||||
float across = Vector3.Distance(a, b) / Fly, rise = Cruise / Climb, drop = (Cruise - Hover) / Climb;
|
||||
float t = (float)(now - trip.w);
|
||||
leg = 0;
|
||||
float span = rise;
|
||||
while (leg < 7)
|
||||
{
|
||||
span = leg == 0 || leg == 6 ? rise : leg == 1 || leg == 5 ? across : leg == 3 ? GrabTime : drop;
|
||||
if (t < span) break;
|
||||
t -= span;
|
||||
leg++;
|
||||
}
|
||||
if (leg == 7) return home;
|
||||
k = Mathf.Clamp01(t / Mathf.Max(0.01f, span));
|
||||
float e = Ease(k);
|
||||
var go = b - a;
|
||||
heading = leg <= 3 ? go : -go;
|
||||
switch (leg)
|
||||
{
|
||||
case 0: return Vector3.Lerp(home, a, e);
|
||||
case 1: return Vector3.Lerp(a, b, e);
|
||||
case 2: return Vector3.Lerp(b, low, e);
|
||||
case 3: return low;
|
||||
case 4: return Vector3.Lerp(low, b, e);
|
||||
case 5: return Vector3.Lerp(b, a, e);
|
||||
default: return Vector3.Lerp(a, home, e);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── every peer: fly them ─────────────────────────
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (_drones[0] == null) return;
|
||||
double now = Now;
|
||||
int count = Count;
|
||||
for (int i = 0; i < Most; i++)
|
||||
{
|
||||
var d = _drones[i];
|
||||
if (!d) continue;
|
||||
bool shown = i < count;
|
||||
if (d.gameObject.activeSelf != shown) d.gameObject.SetActive(shown);
|
||||
if (!shown) continue;
|
||||
var trip = Trip(i).Value;
|
||||
var at = Where(i, trip, now, out int leg, out float k, out var heading);
|
||||
var up = Planet.Up(at);
|
||||
heading = Vector3.ProjectOnPlane(heading, up);
|
||||
var face = heading.sqrMagnitude > 0.01f ? Quaternion.LookRotation(heading, up) : transform.rotation;
|
||||
// nose down while it picks up speed across, a little sway in the hover
|
||||
float lean = leg == 1 || leg == 5 ? Mathf.Sin(k * Mathf.PI) * 14f : 0f;
|
||||
float sway = trip.w >= 0f ? Mathf.Sin(Time.time * 2.1f + i) * 2.5f : 0f;
|
||||
d.SetPositionAndRotation(at, face * Quaternion.Euler(lean, 0f, sway));
|
||||
float spin = trip.w >= 0f ? 1900f : 0f;
|
||||
foreach (var r in _rotors[i]) if (r) r.Rotate(up, spin * Time.deltaTime, Space.World);
|
||||
if (_hum[i]) _hum[i].volume = trip.w >= 0f ? 0.3f * Sfx.SfxVolume : 0f;
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── server: send them out, bring the bundles in ─────────────────────────
|
||||
|
||||
protected override void Update()
|
||||
{
|
||||
if (Belted()) base.Update();
|
||||
if (!IsServer || !IsSpawned) return;
|
||||
double now = Now;
|
||||
bool look = Time.time >= _nextLook;
|
||||
if (look) _nextLook = Time.time + Look;
|
||||
int count = Count;
|
||||
for (int i = 0; i < Most; i++)
|
||||
{
|
||||
var trip = Trip(i).Value;
|
||||
if (trip.w < 0f)
|
||||
{
|
||||
if (look && i < count && !(Piece && Piece.Switched)) Send(i, now);
|
||||
continue;
|
||||
}
|
||||
var at = Where(i, trip, now, out int leg, out float k, out _);
|
||||
var c = _for[i];
|
||||
if (c && (!c.IsSpawned || c.Grab.IsHeld || c.Grab.Consumed || (!_holding[i] && (c.Belt || c.Loaded)))) { Let(i); c = null; }
|
||||
if (c && !_holding[i] && leg >= 3 && leg < 7)
|
||||
{
|
||||
// still where it was when the drone set off? then hook it
|
||||
if ((c.transform.position - new Vector3(trip.x, trip.y, trip.z)).sqrMagnitude < 2.5f * 2.5f) Hook(i, c);
|
||||
else { Let(i); c = null; }
|
||||
}
|
||||
if (c && _holding[i])
|
||||
{
|
||||
var rb = c.Grab.Body;
|
||||
rb.MovePosition(at - Planet.Up(at) * Carry);
|
||||
// down on the pad: into the silo
|
||||
if (leg == 7 || (leg == 6 && k > 0.75f))
|
||||
{
|
||||
Silo.Value += c.Kg.Value;
|
||||
Delivered++;
|
||||
s_claimed.Remove(c);
|
||||
_for[i] = null;
|
||||
_holding[i] = false;
|
||||
c.Grab.Consumed = true;
|
||||
c.NetworkObject.Despawn(true);
|
||||
DeliveredRpc();
|
||||
}
|
||||
}
|
||||
if (leg == 7)
|
||||
{
|
||||
if (_for[i]) Let(i);
|
||||
Trip(i).Value = Parked;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static readonly List<Port> s_ports = new List<Port>();
|
||||
|
||||
/// <summary>Is a belt joined to the hatch?</summary>
|
||||
bool Belted()
|
||||
{
|
||||
s_ports.Clear();
|
||||
Ports(s_ports);
|
||||
return s_ports.Count > 0 && BeltNet.Nearest(s_ports[0].at, true, BeltNet.Joined, Piece, out var next, out _, out _) && next.GetComponentInChildren<Conveyor>();
|
||||
}
|
||||
|
||||
/// <summary>The nearest loose bundle of grass in reach that nobody is after, if the silo has room for it.</summary>
|
||||
void Send(int i, double now)
|
||||
{
|
||||
int out_ = 0;
|
||||
for (int k = 0; k < Most; k++) if (Trip(k).Value.w >= 0f) out_++;
|
||||
if (Silo.Value + (out_ + 1) * GameDefs.BundleKg > Room) return;
|
||||
Cargo best = null;
|
||||
float bestD = Range * Range;
|
||||
var here = transform.position;
|
||||
foreach (var c in Cargo.All)
|
||||
{
|
||||
if (!c || !c.IsSpawned || c.kind != CargoKind.Grass || c.Belt || c.Loaded || s_claimed.Contains(c)) continue;
|
||||
var g = c.Grab;
|
||||
if (!g || g.IsHeld || g.Consumed || !g.Body || g.Body.isKinematic || g.Body.linearVelocity.sqrMagnitude > 0.25f) continue;
|
||||
float d = (c.transform.position - here).sqrMagnitude;
|
||||
// right by the pad: just put out of the hatch, or about to be
|
||||
if (d < 3f * 3f) continue;
|
||||
// dropped off the free end of a belt: that's where someone wants it, and it may be this pad's own
|
||||
if (AtBeltEnd(c.transform.position)) continue;
|
||||
if (d < bestD) { bestD = d; best = c; }
|
||||
}
|
||||
if (!best) return;
|
||||
s_claimed.Add(best);
|
||||
_for[i] = best;
|
||||
_holding[i] = false;
|
||||
var p = best.transform.position;
|
||||
Trip(i).Value = new Vector4(p.x, p.y, p.z, (float)now);
|
||||
}
|
||||
|
||||
static bool AtBeltEnd(Vector3 p)
|
||||
{
|
||||
foreach (var b in Conveyor.All)
|
||||
if (b is BeltRun r && (r.End - p).sqrMagnitude < 2.5f * 2.5f) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
void Hook(int i, Cargo c)
|
||||
{
|
||||
if (c.OwnerClientId != NetworkManager.ServerClientId) c.NetworkObject.ChangeOwnership(NetworkManager.ServerClientId);
|
||||
var rb = c.Grab.Body;
|
||||
rb.linearVelocity = Vector3.zero;
|
||||
rb.angularVelocity = Vector3.zero;
|
||||
rb.isKinematic = true;
|
||||
c.Loaded = true;
|
||||
_holding[i] = true;
|
||||
HookRpc(i);
|
||||
}
|
||||
|
||||
/// <summary>Drone i lets go of its bundle (or of the claim on it): it drops where it is.</summary>
|
||||
void Let(int i)
|
||||
{
|
||||
var c = _for[i];
|
||||
_for[i] = null;
|
||||
if (!c) { _holding[i] = false; return; }
|
||||
s_claimed.Remove(c);
|
||||
if (_holding[i] && c.IsSpawned && !c.Grab.Consumed)
|
||||
{
|
||||
c.Loaded = false;
|
||||
var rb = c.Grab.Body;
|
||||
if (rb) rb.isKinematic = false;
|
||||
}
|
||||
_holding[i] = false;
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void HookRpc(int i)
|
||||
{
|
||||
if (_drones[i]) Sfx.PlayAt("drone_grab", _drones[i].position, 0.5f, 1f, 0.1f, 0.2f);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void DeliveredRpc() => Sfx.PlayAt("cargo_load", transform.position, 0.5f, 1f, 0.1f, 0.4f);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/DronePad.cs.meta
Normal file
2
Assets/Scripts/Gameplay/DronePad.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 93d302c9b3132c94ca2833cf8e1cf9d6
|
||||
314
Assets/Scripts/Gameplay/Foundation.cs
Normal file
314
Assets/Scripts/Gameplay/Foundation.cs
Normal file
@ -0,0 +1,314 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A deck to build on. On the ground: a timber slab, square or hexagonal, 3 m across, its footing sunk into the ground so it
|
||||
/// stays level on a slope; lifted (Ctrl+wheel while placing) it stands on timber stilts down to the soil instead. A storey up:
|
||||
/// a floor or a flat roof resting on walls. What stands on a deck sits on a half-metre grid and turns with it, walls go on its
|
||||
/// edges, and neighbouring decks of a kind line up edge to edge at the same height.
|
||||
/// </summary>
|
||||
public class Foundation : MonoBehaviour
|
||||
{
|
||||
public const float Across = 3f, Top = 0.3f, Sunk = 1.5f;
|
||||
/// <summary>A slab lifted more than this stands on stilts; a raised deck is this deep.</summary>
|
||||
public const float Stilts = 0.25f, DeckDepth = 0.4f;
|
||||
/// <summary>How high a foundation can be lifted off the ground.</summary>
|
||||
public const float MaxRaise = 6f;
|
||||
|
||||
/// <summary>Height of a deck's walking surface above its origin: foundations stand on the ground, floors hang from their top.</summary>
|
||||
public static float TopOf(PieceId id) => GameDefs.IsFoundation(id) ? Top : 0f;
|
||||
|
||||
static Mesh s_square, s_hex, s_squareDeck, s_hexDeck, s_floor;
|
||||
|
||||
static float SquareR => Across * Mathf.Sqrt(0.5f);
|
||||
static float HexR => Across * 0.5f / Mathf.Cos(30f * Mathf.Deg2Rad);
|
||||
|
||||
public static Mesh Shape(PieceId id, bool raised = false)
|
||||
{
|
||||
if (id == PieceId.Floor || id == PieceId.FlatRoof) return s_floor ? s_floor : (s_floor = Slab(4, SquareR, 45f, 0f, -0.3f));
|
||||
if (id == PieceId.Hex)
|
||||
{
|
||||
if (raised) return s_hexDeck ? s_hexDeck : (s_hexDeck = Slab(6, HexR, 30f, Top, Top - DeckDepth));
|
||||
return s_hex ? s_hex : (s_hex = Slab(6, HexR, 30f, Top, -Sunk));
|
||||
}
|
||||
if (raised) return s_squareDeck ? s_squareDeck : (s_squareDeck = Slab(4, SquareR, 45f, Top, Top - DeckDepth));
|
||||
return s_square ? s_square : (s_square = Slab(4, SquareR, 45f, Top, -Sunk));
|
||||
}
|
||||
|
||||
/// <summary>A flat-topped prism with the corners on a circle.</summary>
|
||||
static Mesh Slab(int sides, float radius, float turn, float top, float bottom)
|
||||
{
|
||||
var v = new List<Vector3>();
|
||||
var n = new List<Vector3>();
|
||||
var uv = new List<Vector2>();
|
||||
var t = new List<int>();
|
||||
Vector3 Corner(int i, float y)
|
||||
{
|
||||
float a = (turn + i * 360f / sides) * Mathf.Deg2Rad;
|
||||
return new Vector3(Mathf.Sin(a) * radius, y, Mathf.Cos(a) * radius);
|
||||
}
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
v.Add(Corner(i, top));
|
||||
n.Add(Vector3.up);
|
||||
uv.Add(new Vector2(v[i].x, v[i].z));
|
||||
}
|
||||
for (int i = 1; i < sides - 1; i++) { t.Add(0); t.Add(i); t.Add(i + 1); }
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
int b = v.Count;
|
||||
Vector3 p = Corner(i, top), q = Corner(i + 1, top), r = Corner(i + 1, bottom), s = Corner(i, bottom);
|
||||
var face = Vector3.Cross(r - p, q - p).normalized;
|
||||
v.Add(p); v.Add(q); v.Add(r); v.Add(s);
|
||||
n.Add(face); n.Add(face); n.Add(face); n.Add(face);
|
||||
uv.Add(new Vector2(0f, top)); uv.Add(new Vector2(Across, top)); uv.Add(new Vector2(Across, bottom)); uv.Add(new Vector2(0f, bottom));
|
||||
t.Add(b); t.Add(b + 2); t.Add(b + 1);
|
||||
t.Add(b); t.Add(b + 3); t.Add(b + 2);
|
||||
}
|
||||
// the underside, so a raised deck isn't hollow from below
|
||||
int u = v.Count;
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
v.Add(Corner(i, bottom));
|
||||
n.Add(Vector3.down);
|
||||
uv.Add(new Vector2(v[u + i].x, v[u + i].z));
|
||||
}
|
||||
for (int i = 1; i < sides - 1; i++) { t.Add(u); t.Add(u + i + 1); t.Add(u + i); }
|
||||
var m = new Mesh { name = "Slab" + sides };
|
||||
m.SetVertices(v);
|
||||
m.SetNormals(n);
|
||||
m.SetUVs(0, uv);
|
||||
m.SetTriangles(t, 0);
|
||||
m.RecalculateBounds();
|
||||
return m;
|
||||
}
|
||||
|
||||
BuildPiece _piece;
|
||||
MeshCollider _collider;
|
||||
Transform _slab, _model, _stilts;
|
||||
bool _raised;
|
||||
Vector3 _fitAt = new Vector3(float.NaN, 0f, 0f);
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_piece = GetComponent<BuildPiece>();
|
||||
var slab = new GameObject("Slab") { layer = gameObject.layer };
|
||||
slab.transform.SetParent(transform, false);
|
||||
_slab = slab.transform;
|
||||
_collider = slab.AddComponent<MeshCollider>();
|
||||
_collider.sharedMesh = Shape(_piece.piece);
|
||||
_collider.convex = true;
|
||||
Dress(_piece.Def.model);
|
||||
}
|
||||
|
||||
void Start() => Fit();
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if ((transform.position - _fitAt).sqrMagnitude > 1e-4f) Fit();
|
||||
}
|
||||
|
||||
void Dress(string name)
|
||||
{
|
||||
if (_model) Destroy(_model.gameObject);
|
||||
_model = null;
|
||||
var model = AssetBank.I ? AssetBank.I.Model(name) : null;
|
||||
if (!model) return;
|
||||
var deck = Instantiate(model, _slab);
|
||||
foreach (var other in deck.GetComponentsInChildren<Collider>(true)) Destroy(other);
|
||||
_model = deck.transform;
|
||||
}
|
||||
|
||||
/// <summary>Lifted off the ground: the deck alone on stilts down to the soil; on the ground, the slab with its footing.</summary>
|
||||
void Fit()
|
||||
{
|
||||
_fitAt = transform.position;
|
||||
if (!GameDefs.IsFoundation(_piece.piece)) return;
|
||||
bool raised = Planet.Altitude(transform.position) > Stilts;
|
||||
if (raised != _raised)
|
||||
{
|
||||
_raised = raised;
|
||||
_collider.sharedMesh = Shape(_piece.piece, raised);
|
||||
string deck = _piece.piece == PieceId.Hex ? "SM_Deck_Hex" : "SM_Deck_Square";
|
||||
Dress(raised && AssetBank.I && AssetBank.I.Model(deck) ? deck : _piece.Def.model);
|
||||
}
|
||||
if (_stilts) Destroy(_stilts.gameObject);
|
||||
_stilts = null;
|
||||
if (raised) Stand();
|
||||
}
|
||||
|
||||
/// <summary>Timber legs from under the deck to the soil, braced where they're tall.</summary>
|
||||
void Stand()
|
||||
{
|
||||
_stilts = new GameObject("Stilts") { layer = gameObject.layer }.transform;
|
||||
_stilts.SetParent(transform, false);
|
||||
var wood = BuildLook.Mat("M_Timber", new Color(0.55f, 0.4f, 0.25f));
|
||||
int sides = _piece.piece == PieceId.Hex ? 6 : 4;
|
||||
float reach = (sides == 6 ? HexR : SquareR) - 0.32f, turn = sides == 6 ? 30f : 45f;
|
||||
float under = Top - DeckDepth;
|
||||
var feet = new Vector3[sides];
|
||||
var lengths = new float[sides];
|
||||
// the turn alone, not the bounce the piece lands with: the ground is measured in metres
|
||||
var rot = transform.rotation;
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
float a = (turn + i * 360f / sides) * Mathf.Deg2Rad;
|
||||
var foot = new Vector3(Mathf.Sin(a) * reach, under, Mathf.Cos(a) * reach);
|
||||
float drop = Mathf.Max(0.2f, Planet.Altitude(transform.position + rot * foot)) + 0.35f;
|
||||
feet[i] = foot;
|
||||
lengths[i] = drop;
|
||||
Beam(wood, foot + Vector3.down * drop * 0.5f, Quaternion.identity, new Vector3(0.22f, drop, 0.22f));
|
||||
// a stone pad where it meets the soil
|
||||
Beam(BuildLook.Mat("M_Stone", new Color(0.55f, 0.54f, 0.5f)), foot + Vector3.down * (drop - 0.3f), Quaternion.identity, new Vector3(0.42f, 0.16f, 0.42f));
|
||||
}
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
int j = (i + 1) % sides;
|
||||
float tall = Mathf.Min(lengths[i], lengths[j]) - 0.35f;
|
||||
if (tall < 0.9f) continue;
|
||||
// a rail under the deck and a diagonal brace on each side
|
||||
var a = feet[i] + Vector3.down * 0.25f;
|
||||
var b = feet[j] + Vector3.down * Mathf.Min(tall * 0.8f, 2.6f);
|
||||
Strut(wood, feet[i] + Vector3.down * 0.18f, feet[j] + Vector3.down * 0.18f, 0.12f);
|
||||
Strut(wood, a, b, 0.1f);
|
||||
}
|
||||
}
|
||||
|
||||
void Strut(Material m, Vector3 a, Vector3 b, float w)
|
||||
{
|
||||
var d = b - a;
|
||||
Beam(m, (a + b) * 0.5f, Quaternion.LookRotation(d), new Vector3(w, w * 1.2f, d.magnitude));
|
||||
}
|
||||
|
||||
void Beam(Material m, Vector3 at, Quaternion rot, Vector3 size)
|
||||
{
|
||||
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
go.name = "Stilt";
|
||||
go.layer = gameObject.layer;
|
||||
go.transform.SetParent(_stilts, false);
|
||||
go.transform.localPosition = at;
|
||||
go.transform.localRotation = rot;
|
||||
go.transform.localScale = size;
|
||||
go.GetComponent<Renderer>().sharedMaterial = m;
|
||||
}
|
||||
|
||||
/// <summary>Half-metre grid on a deck, level with its top.</summary>
|
||||
public static Vector3 Grid(Transform slab, Vector3 point)
|
||||
{
|
||||
var piece = slab.GetComponent<BuildPiece>();
|
||||
var l = Quaternion.Inverse(slab.rotation) * (point - slab.position);
|
||||
l.x = Mathf.Round(l.x * 2f) * 0.5f;
|
||||
l.z = Mathf.Round(l.z * 2f) * 0.5f;
|
||||
l.y = piece ? TopOf(piece.piece) : Top;
|
||||
return slab.position + slab.rotation * l;
|
||||
}
|
||||
|
||||
/// <summary>The spot next to a deck of the same kind nearest to a point, edge to edge with it and at its height.</summary>
|
||||
public static bool Beside(Vector3 point, PieceId id, out Vector3 at, out Quaternion rot)
|
||||
{
|
||||
at = point; rot = Quaternion.identity;
|
||||
BuildPiece near = null;
|
||||
float best = 36f;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || !GameDefs.IsDeck(p.piece)) continue;
|
||||
float d = (p.transform.position + p.transform.rotation * Vector3.up * TopOf(p.piece) - point).sqrMagnitude;
|
||||
if (d < best) { best = d; near = p; }
|
||||
}
|
||||
if (!near || near.piece != id) return false;
|
||||
int sides = id == PieceId.Hex ? 6 : 4;
|
||||
var t = near.transform;
|
||||
rot = t.rotation;
|
||||
best = float.MaxValue;
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
var c = t.position + t.rotation * (Quaternion.Euler(0f, i * 360f / sides, 0f) * Vector3.forward) * Across;
|
||||
float d = (c - point).sqrMagnitude;
|
||||
if (d < best) { best = d; at = c; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where walls, floors and roofs go: walls on the edges of a square deck, floors and roofs on top of the walls.</summary>
|
||||
public static class Snap
|
||||
{
|
||||
/// <summary>The edge of the square deck nearest to the point, facing out (or in, every other turn of R).</summary>
|
||||
public static bool Edge(Vector3 point, BuildPiece on, float yaw, out Vector3 at, out Quaternion rot)
|
||||
{
|
||||
at = point; rot = Quaternion.identity;
|
||||
var deck = on && GameDefs.IsSquareDeck(on.piece) ? on : null;
|
||||
if (!deck)
|
||||
{
|
||||
float near = 4.5f * 4.5f;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || !GameDefs.IsSquareDeck(p.piece)) continue;
|
||||
float d = (Top(p) - point).sqrMagnitude;
|
||||
if (d < near) { near = d; deck = p; }
|
||||
}
|
||||
}
|
||||
if (!deck) return false;
|
||||
var t = deck.transform;
|
||||
var c = Top(deck);
|
||||
float best = float.MaxValue;
|
||||
var outward = t.rotation * Vector3.forward;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var dir = t.rotation * (Quaternion.Euler(0f, i * 90f, 0f) * Vector3.forward);
|
||||
var e = c + dir * Foundation.Across * 0.5f;
|
||||
float d = (e - point).sqrMagnitude;
|
||||
if (d < best) { best = d; at = e; outward = dir; }
|
||||
}
|
||||
if (Mathf.Repeat(yaw, 360f) >= 180f) outward = -outward;
|
||||
rot = Quaternion.LookRotation(outward, t.rotation * Vector3.up);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A storey up: aimed at a wall (or a pillar), the 3 m cell beside it on the side you're looking from, level with its top;
|
||||
/// a pitched roof's eave goes along that wall. Standing on a floor, a pitched roof goes on the floor itself.
|
||||
/// </summary>
|
||||
public static bool OnTop(PieceId id, Vector3 point, BuildPiece target, BuildPiece on, float yaw, out Vector3 at, out Quaternion rot)
|
||||
{
|
||||
at = point; rot = Quaternion.identity;
|
||||
var spin = Quaternion.Euler(0f, Mathf.Round(yaw / 90f) * 90f, 0f);
|
||||
if (target && GameDefs.Holds(target.piece))
|
||||
{
|
||||
var t = target.transform;
|
||||
var up = t.rotation * Vector3.up;
|
||||
var top = t.position + up * GameDefs.Storey;
|
||||
Vector3 cell;
|
||||
if (target.piece == PieceId.Pillar)
|
||||
{
|
||||
var l = Quaternion.Inverse(t.rotation) * (point - top);
|
||||
cell = top + t.rotation * new Vector3(Mathf.Sign(l.x) * 1.5f, 0f, Mathf.Sign(l.z) * 1.5f);
|
||||
}
|
||||
else
|
||||
{
|
||||
var f = t.rotation * Vector3.forward;
|
||||
var inside = top - f * 1.5f;
|
||||
var outside = top + f * 1.5f;
|
||||
cell = (inside - point).sqrMagnitude <= (outside - point).sqrMagnitude ? inside : outside;
|
||||
}
|
||||
var toWall = top - cell;
|
||||
toWall = Vector3.ProjectOnPlane(toWall, up);
|
||||
if (toWall.sqrMagnitude < 0.01f) toWall = t.rotation * Vector3.forward;
|
||||
at = cell;
|
||||
rot = Quaternion.LookRotation(toWall.normalized, up) * spin;
|
||||
return true;
|
||||
}
|
||||
if (id == PieceId.Roof && on && GameDefs.IsSquareDeck(on.piece))
|
||||
{
|
||||
at = Top(on);
|
||||
rot = on.transform.rotation * spin;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static Vector3 Top(BuildPiece deck) => deck.transform.position + deck.transform.rotation * Vector3.up * Foundation.TopOf(deck.piece);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Foundation.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Foundation.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e3ef451b3573bec4c8c45723012d2023
|
||||
564
Assets/Scripts/Gameplay/GameDefs.cs
Normal file
564
Assets/Scripts/Gameplay/GameDefs.cs
Normal file
@ -0,0 +1,564 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>What a player can hold: six hand tools from nail scissors to the two-handed scythe, each with its own
|
||||
/// grass container, and the hammer that opens the build menu.</summary>
|
||||
public enum ToolId : byte { NailScissors = 0, GardenShears = 1, Sickle = 2, Scythe = 3, LongScythe = 4, WideScythe = 5, Hammer = 6, LawnMower = 7, None = 255 }
|
||||
|
||||
/// <summary>Personal gear on the supply wall; shares the owned mask with the tools.</summary>
|
||||
public enum GearId : byte { Jetpack = 8, Boots = 9, NightVision = 10 }
|
||||
|
||||
public enum CargoKind : byte { Grass = 0, Hay = 1, Brick = 2 }
|
||||
|
||||
public enum VehicleKind : byte { Push, Rider, Pickup, Tractor, Combine, Hauler, Mulcher, Baler, Count }
|
||||
|
||||
public enum TuneId : byte { Motors, Hopper, Turbo, Cruise, Cutter, Release, Lights, Count }
|
||||
|
||||
public enum PerkTree : byte { Containers = 0, Cutting = 1, Suit = 2, Logistics = 3, Economy = 4 }
|
||||
|
||||
public enum PerkId : byte
|
||||
{
|
||||
// CONTAINERS
|
||||
BinScissors, BinShears, BinSickle, BinScythe, BinLongScythe, BinWideScythe, Compactor, AutoBaler,
|
||||
// CUTTING
|
||||
WiderBlades, LongHandles, DeepSwath, WhetSteel,
|
||||
// SUIT
|
||||
ServoBoots, SpringStep, FieldFrame,
|
||||
// LOGISTICS
|
||||
QuickTwine, BundleLine, ThrowArm, ExpressDepot,
|
||||
// ECONOMY
|
||||
EarthPrices, RegionBonus, SupplyDeals, GreenExchange,
|
||||
Count
|
||||
}
|
||||
|
||||
public enum PieceCat : byte { Services, Logistics, Production, Power, Structures, Decor, Count }
|
||||
|
||||
public enum PieceId : byte { Depot, Belt, Splitter, Merger, Square, Hex, Dryer, Press, SolarS, SolarM, SolarL, Garage, Binder, RobotI, RobotII, Reaper, Catcher, Pole, BatteryS, BatteryL, UnloadBay, DronePad, Intake,
|
||||
Wall, WindowWall, DoorWall, Railing, Fence, Floor, FlatRoof, Roof, Stairs, Steps, Pillar, Planter, Lamppost, Bench, Crates, Flagpole, Count }
|
||||
|
||||
/// <summary>How a structure finds its place: anywhere, on the edge of a deck, or on top of the walls (a storey up).</summary>
|
||||
public enum Fit : byte { Free, Edge, Top }
|
||||
|
||||
public class ToolDef
|
||||
{
|
||||
public ToolId id;
|
||||
public string nameEn, descEn, icon, model;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public float width; // metres
|
||||
public float capacity; // kilos
|
||||
public long price;
|
||||
}
|
||||
|
||||
public class PerkDef
|
||||
{
|
||||
public PerkId id;
|
||||
public PerkTree tree;
|
||||
public string nameEn, descEn, icon;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public int col, row;
|
||||
/// <summary>Price of each level, in order.</summary>
|
||||
public long[] prices = { 0 };
|
||||
public bool big; // a big step: drawn bigger
|
||||
public PerkId[] requires = new PerkId[0];
|
||||
public int requireLevel = 1;
|
||||
public System.Func<int, string> effect;
|
||||
|
||||
public int maxLevel => prices.Length;
|
||||
public long PriceFor(int currentLevel) => prices[Mathf.Clamp(currentLevel, 0, prices.Length - 1)];
|
||||
public string EffectFor(int level) => effect != null ? effect(level) : desc;
|
||||
}
|
||||
|
||||
public class PieceDef
|
||||
{
|
||||
public PieceId id;
|
||||
public PieceCat cat;
|
||||
public string nameEn, descEn, icon, model, prefab;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public double price;
|
||||
public int sizeX = 1, sizeZ = 1;
|
||||
/// <summary>How much bigger than its file the model is built.</summary>
|
||||
public float scale = 1f;
|
||||
/// <summary>Kilowatts a machine draws while it works.</summary>
|
||||
public float kw;
|
||||
/// <summary>Company equipment: never in the build menu.</summary>
|
||||
public bool company;
|
||||
}
|
||||
|
||||
/// <summary>What a machine turns into what, batch by batch.</summary>
|
||||
public class RecipeDef
|
||||
{
|
||||
public float grass, hay, seconds, makes;
|
||||
public CargoKind product;
|
||||
}
|
||||
|
||||
public class VehicleDef
|
||||
{
|
||||
public VehicleKind kind;
|
||||
public string nameEn, descEn, icon;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public double price;
|
||||
/// <summary>Strip it cuts, kilos it holds, bundles on the bed. A pickup cuts nothing.</summary>
|
||||
public float width, hopper;
|
||||
public int bed;
|
||||
public float speed, accel, turn;
|
||||
/// <summary>The crew are tall in the head: how far the seat sits below where the model has it, to keep them under the roof.</summary>
|
||||
public float seatDrop;
|
||||
public float seatAhead;
|
||||
/// <summary>Feeds its hopper onto a belt as bundles from a chute on its right, wherever a belt starts beside it.</summary>
|
||||
public bool bales;
|
||||
}
|
||||
|
||||
/// <summary>One upgrade a machine can take, level by level.</summary>
|
||||
public class TuneDef
|
||||
{
|
||||
public TuneId id;
|
||||
public string nameEn;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public long[] prices;
|
||||
public System.Func<int, string> effect;
|
||||
}
|
||||
|
||||
/// <summary>What drives itself: rings of sectors it works (0 = all of them), strip, walking speed, hopper.</summary>
|
||||
/// <summary>What a piece's upgrade levels change.</summary>
|
||||
public enum UpgradeKind { None, Belt, Machine, Robot, Silo }
|
||||
|
||||
public class RobotDef
|
||||
{
|
||||
public PieceId piece;
|
||||
public string nameEn;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public int reach;
|
||||
public float width, speed, hopper;
|
||||
}
|
||||
|
||||
public class PanelDef
|
||||
{
|
||||
public float kw, radius;
|
||||
public bool tracker;
|
||||
}
|
||||
|
||||
public class BatteryDef
|
||||
{
|
||||
public float kwh, kw, radius;
|
||||
}
|
||||
|
||||
public static class GameDefs
|
||||
{
|
||||
// ───────────────────────── world ─────────────────────────
|
||||
|
||||
/// <summary>The soil around the base (the deck top is y = 0; the deck stands on stilts above the meadow).</summary>
|
||||
public const float WaterY = -1.2f;
|
||||
/// <summary>The whole of Herbaria-7: 163 842 sectors of about 600 m² each. Easier games play on a smaller ball (<see cref="Planet.Radius"/>).</summary>
|
||||
public const float PlanetRadius = 2797f;
|
||||
public const float TileSize = 6f;
|
||||
/// <summary>The meadow is this tall, everywhere, until it is cut.</summary>
|
||||
public const float GrassHeight = 0.42f;
|
||||
|
||||
/// <summary>Kilos of grass on a square metre of meadow.</summary>
|
||||
public const float GrassDensity = 0.25f;
|
||||
/// <summary>Herbaria-7: 163 830 hex sectors of about 600 m² (the base and the planet size live here).</summary>
|
||||
public const int Sectors = 163830;
|
||||
/// <summary>About 600 m² on the whole planet, a quarter of that on half of it, a ninth on a third.</summary>
|
||||
public static float SectorArea => 4f * Mathf.PI * Planet.Radius * Planet.Radius / HexGrid.Cells;
|
||||
public static double PlanetKg => Sectors * (double)SectorArea * GrassDensity;
|
||||
public static double PlanetArea => Sectors * (double)SectorArea;
|
||||
/// <summary>A sector mown clean pays on top of its grass.</summary>
|
||||
public static double SectorBonus(int bounty) => 10d + bounty * 15d;
|
||||
public const double StakePay = 100d, PointPay = 250d;
|
||||
|
||||
// ───────────────────────── tools ─────────────────────────
|
||||
|
||||
public static readonly ToolDef[] Tools =
|
||||
{
|
||||
new ToolDef { id = ToolId.NailScissors, name = Loc.N("Nail Scissors"), icon = "icon_tool_scissors", model = "SM_Tool_NailScissors", width = 0.12f, capacity = 0.5f, price = 0,
|
||||
desc = Loc.N("Company issue. For a whole planet. Earth is counting on you.") },
|
||||
new ToolDef { id = ToolId.GardenShears, name = Loc.N("Garden Shears"), icon = "icon_tool_shears", model = "SM_Tool_GardenShears", width = 0.18f, capacity = 0.75f, price = 5,
|
||||
desc = Loc.N("A proper pair of shears. Your wrist says thank you.") },
|
||||
new ToolDef { id = ToolId.Sickle, name = Loc.N("Sickle"), icon = "icon_tool_sickle", model = "SM_Tool_Sickle", width = 0.24f, capacity = 1f, price = 10,
|
||||
desc = Loc.N("A one-handed hooked blade with a small grass sack.") },
|
||||
new ToolDef { id = ToolId.Scythe, name = Loc.N("Scythe"), icon = "icon_tool_scythe", model = "SM_Tool_Scythe", width = 0.43f, capacity = 3f, price = 25,
|
||||
desc = Loc.N("The real thing: long strokes and a proper basket on the back.") },
|
||||
new ToolDef { id = ToolId.LongScythe, name = Loc.N("Long Scythe"), icon = "icon_tool_longscythe", model = "SM_Tool_LongScythe", width = 0.65f, capacity = 6f, price = 75,
|
||||
desc = Loc.N("A longer blade, a wider strip, a bigger basket.") },
|
||||
new ToolDef { id = ToolId.WideScythe, name = Loc.N("Two-Handed Scythe"), icon = "icon_tool_widescythe", model = "SM_Tool_WideScythe", width = 0.988f, capacity = 12f, price = 150,
|
||||
desc = Loc.N("Almost a metre of steel. Earth will be green by Christmas.") },
|
||||
new ToolDef { id = ToolId.Hammer, name = Loc.N("Build Hammer"), icon = "icon_tool_hammer", model = "SM_Tool_Hammer", price = 50,
|
||||
desc = Loc.N("Opens the build menu. Q category, wheel piece, R rotate, RMB remove.") },
|
||||
new ToolDef { id = ToolId.LawnMower, name = Loc.N("Lawn Mower"), icon = "icon_tool_lawnmower", model = "SM_Tool_LawnMower", width = 1.1f, capacity = 30f, price = 400,
|
||||
desc = Loc.N("A wide-deck push mower. Hold the mouse and walk: it cuts the strip under it as you go.") },
|
||||
};
|
||||
|
||||
/// <summary>How many tool ids there are, and the order the supply wall and the belt list them: blades by size, then the hammer.</summary>
|
||||
public const int ToolCount = 8;
|
||||
public static readonly ToolId[] ToolOrder = { ToolId.NailScissors, ToolId.GardenShears, ToolId.Sickle, ToolId.Scythe, ToolId.LongScythe, ToolId.WideScythe, ToolId.LawnMower, ToolId.Hammer };
|
||||
|
||||
public static ToolDef Tool(ToolId id) => Tools[(int)id];
|
||||
public static bool IsBlade(ToolId t) => t <= ToolId.WideScythe || t == ToolId.LawnMower;
|
||||
/// <summary>Pushed along the ground instead of swung: cuts under its deck while you walk.</summary>
|
||||
public static bool IsMower(ToolId t) => t == ToolId.LawnMower;
|
||||
/// <summary>Scythes and shears have a basket perk each; the mower's bag only grows with the compactor.</summary>
|
||||
public static bool HasBinPerk(ToolId t) => t <= ToolId.WideScythe;
|
||||
public static PerkId BinPerk(ToolId t) => (PerkId)((int)PerkId.BinScissors + (int)t);
|
||||
|
||||
public const int MaxBeltSlots = 6;
|
||||
/// <summary>Price of the next belt slot when you already have this many.</summary>
|
||||
public static long BeltSlotPrice(int have) => 15L << Mathf.Clamp(have - 1, 0, MaxBeltSlots);
|
||||
public const long JetpackPrice = 300, BootsPrice = 250, NightVisionPrice = 350;
|
||||
public static long GearPrice(GearId g) => g == GearId.Boots ? BootsPrice : g == GearId.NightVision ? NightVisionPrice : JetpackPrice;
|
||||
public const float JetDash = 11f, JetCooldown = 2.5f;
|
||||
/// <summary>Herbaria-7 pulls weakly: this is how fast the crew and loose bundles fall, and how hard you jump.
|
||||
/// The gravity boots bring back Earth's pull (the player's own gravity and jump).</summary>
|
||||
public const float LowGravity = 7.6f, LowJump = 5.4f;
|
||||
|
||||
// ───────────────────────── upgrade matrix ─────────────────────────
|
||||
|
||||
static PerkDef Bin(PerkId id, string name, string desc, int col, params long[] prices) => new PerkDef
|
||||
{
|
||||
id = id, tree = PerkTree.Containers, name = name, icon = "icon_perk_backpack", col = col, row = 0, prices = prices,
|
||||
desc = desc,
|
||||
effect = l => Loc.F("Container x{0:0}", BinMul(l)),
|
||||
};
|
||||
|
||||
public static readonly PerkDef[] Perks =
|
||||
{
|
||||
// ── CONTAINERS ──
|
||||
Bin(PerkId.BinScissors, Loc.N("Nail Scissors Basket"), Loc.N("A bigger basket for the Nail Scissors."), 0, 10, 25, 60),
|
||||
Bin(PerkId.BinShears, Loc.N("Garden Shears Basket"), Loc.N("A bigger basket for the Garden Shears."), 1, 15, 40, 100),
|
||||
Bin(PerkId.BinSickle, Loc.N("Sickle Basket"), Loc.N("A bigger basket for the Sickle."), 2, 20, 50, 120),
|
||||
Bin(PerkId.BinScythe, Loc.N("Scythe Basket"), Loc.N("A bigger basket for the Scythe."), 3, 30, 80, 190),
|
||||
Bin(PerkId.BinLongScythe, Loc.N("Long Scythe Basket"), Loc.N("A bigger basket for the Long Scythe."), 4, 45, 110, 260),
|
||||
Bin(PerkId.BinWideScythe, Loc.N("Two-Handed Scythe Basket"), Loc.N("A bigger basket for the Two-Handed Scythe."), 5, 55, 140, 320),
|
||||
new PerkDef { id = PerkId.Compactor, tree = PerkTree.Containers, name = Loc.N("Grass Compactor"), icon = "icon_perk_pressure", col = 2, row = 1, prices = new long[] { 150, 450, 1200 },
|
||||
desc = Loc.N("Tread it down harder. Every tool holds more."), effect = l => Loc.F("All tools +{0}%", l * 15) },
|
||||
new PerkDef { id = PerkId.AutoBaler, tree = PerkTree.Containers, name = Loc.N("Auto-Binder"), icon = "icon_piece_filler", col = 3, row = 2, prices = new long[] { 2000 }, big = true, requires = new[] { PerkId.Compactor }, requireLevel = 2,
|
||||
desc = Loc.N("A full basket ties itself into a bundle and drops it at your feet.") },
|
||||
|
||||
// ── CUTTING ──
|
||||
new PerkDef { id = PerkId.WiderBlades, tree = PerkTree.Cutting, name = Loc.N("Wider Blades"), icon = "icon_perk_suction", col = 0, row = 0, prices = new long[] { 40, 140, 400 },
|
||||
desc = Loc.N("A wider strip with every tool."), effect = l => Loc.F("Strip width +{0:0}%", WidthBonus(l) * 100f) },
|
||||
new PerkDef { id = PerkId.LongHandles, tree = PerkTree.Cutting, name = Loc.N("Long Handles"), icon = "icon_perk_nozzle", col = 1, row = 0, prices = new long[] { 70, 220 },
|
||||
desc = Loc.N("Reach further without taking a step."), effect = l => Loc.F("Reach +{0:0.##} m", l * 0.75f) },
|
||||
new PerkDef { id = PerkId.DeepSwath, tree = PerkTree.Cutting, name = Loc.N("Deep Swath"), icon = "icon_perk_flow", col = 2, row = 0, prices = new long[] { 90, 280 },
|
||||
desc = Loc.N("The blade bites deeper into the grass."), effect = l => Loc.F("Strip width +{0:0}%", l * 6) },
|
||||
new PerkDef { id = PerkId.WhetSteel, tree = PerkTree.Cutting, name = Loc.N("Whetstone Steel"), icon = "icon_perk_blast", col = 1, row = 1, prices = new long[] { 1500 }, big = true, requires = new[] { PerkId.WiderBlades, PerkId.LongHandles, PerkId.DeepSwath }, requireLevel = 2,
|
||||
desc = Loc.N("A razor edge: +10% width and depth, +0.5 m reach.") },
|
||||
|
||||
// ── SUIT ──
|
||||
new PerkDef { id = PerkId.ServoBoots, tree = PerkTree.Suit, name = Loc.N("Servo Boots"), icon = "icon_perk_sneakers", col = 0, row = 0, prices = new long[] { 50, 160, 450 },
|
||||
desc = Loc.N("Move faster."), effect = l => Loc.F("Speed +{0}%", l * 7) },
|
||||
new PerkDef { id = PerkId.SpringStep, tree = PerkTree.Suit, name = Loc.N("Spring Step"), icon = "icon_perk_boots", col = 2, row = 0, prices = new long[] { 80, 250 },
|
||||
desc = Loc.N("Jump higher."), effect = l => Loc.F("Jump +{0}%", l * 20) },
|
||||
new PerkDef { id = PerkId.FieldFrame, tree = PerkTree.Suit, name = Loc.N("Field Frame"), icon = "icon_perk_fins", col = 1, row = 1, prices = new long[] { 1200 }, big = true, requires = new[] { PerkId.ServoBoots, PerkId.SpringStep }, requireLevel = 2,
|
||||
desc = Loc.N("A light exoskeleton: +8% speed, +15% jump.") },
|
||||
|
||||
// ── LOGISTICS ──
|
||||
new PerkDef { id = PerkId.QuickTwine, tree = PerkTree.Logistics, name = Loc.N("Quick Twine"), icon = "icon_perk_release", col = 0, row = 0, prices = new long[] { 30, 100, 300 },
|
||||
desc = Loc.N("Tie bundles faster."), effect = l => Loc.F("Bundle time -{0}%", l switch { 1 => 25, 2 => 44, _ => 58 }) },
|
||||
new PerkDef { id = PerkId.BundleLine, tree = PerkTree.Logistics, name = Loc.N("Bundle Line"), icon = "icon_perk_remote", col = 1, row = 0, prices = new long[] { 60, 200 },
|
||||
desc = Loc.N("Grab bundles from further away."), effect = l => Loc.F("Pick-up reach +{0:0.#} m", l * 1.5f) },
|
||||
new PerkDef { id = PerkId.ThrowArm, tree = PerkTree.Logistics, name = Loc.N("Throwing Arm"), icon = "icon_perk_beltspeed", col = 2, row = 0, prices = new long[] { 80, 240 },
|
||||
desc = Loc.N("Throw bundles further."), effect = l => Loc.F("Throw +{0}%", l * 25) },
|
||||
new PerkDef { id = PerkId.ExpressDepot, tree = PerkTree.Logistics, name = Loc.N("Express Depot"), icon = "icon_perk_dockpump", col = 1, row = 1, prices = new long[] { 900 }, big = true, requires = new[] { PerkId.QuickTwine }, requireLevel = 2,
|
||||
desc = Loc.N("Bundles tie twice as fast and machines unload at the depot twice as fast.") },
|
||||
|
||||
// ── ECONOMY ──
|
||||
new PerkDef { id = PerkId.EarthPrices, tree = PerkTree.Economy, name = Loc.N("Earth Prices"), icon = "icon_perk_contracts", col = 0, row = 0, prices = new long[] { 120, 400, 1100 },
|
||||
desc = Loc.N("Earth is desperate for grass. Make it pay."), effect = l => Loc.F("Payout +{0}%", l * 6) },
|
||||
new PerkDef { id = PerkId.RegionBonus, tree = PerkTree.Economy, name = Loc.N("Sector Bounty"), icon = "icon_perk_purity", col = 2, row = 0, prices = new long[] { 200, 600 },
|
||||
desc = Loc.N("More cash for every sector mown clean."), effect = l => Loc.F("+{0} per sector", UIK.Money(l * 15d)) },
|
||||
new PerkDef { id = PerkId.SupplyDeals, tree = PerkTree.Economy, name = Loc.N("Supply Deals"), icon = "icon_perk_overclock", col = 0, row = 1, prices = new long[] { 250, 700 },
|
||||
desc = Loc.N("Tools at the supply wall get cheaper."), effect = l => Loc.F("Tools -{0}%", l * 5) },
|
||||
new PerkDef { id = PerkId.GreenExchange, tree = PerkTree.Economy, name = Loc.N("Green Exchange"), icon = "icon_star", col = 1, row = 2, prices = new long[] { 2500 }, big = true, requires = new[] { PerkId.EarthPrices }, requireLevel = 2,
|
||||
desc = Loc.N("A seat on the Earth grass exchange: +10% on every payout.") },
|
||||
};
|
||||
|
||||
public static PerkDef Perk(PerkId id) => Perks[(int)id];
|
||||
|
||||
// ───────────────────────── build pieces ─────────────────────────
|
||||
|
||||
public static readonly PieceDef[] Pieces =
|
||||
{
|
||||
new PieceDef { id = PieceId.Depot, cat = PieceCat.Services, company = true, name = Loc.N("Grass Depot"), icon = "icon_piece_hopper", model = "SM_Hopper", prefab = "Piece_Depot", sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("Everything that goes in here is paid for and shipped to Earth.") },
|
||||
new PieceDef { id = PieceId.Belt, cat = PieceCat.Logistics, name = Loc.N("Belt"), icon = "icon_piece_belt", model = "SM_Belt", prefab = "Piece_Belt", price = 0.5,
|
||||
desc = Loc.N("A straight run: click where it starts, click where it ends.") },
|
||||
new PieceDef { id = PieceId.Splitter, cat = PieceCat.Logistics, name = Loc.N("Splitter"), icon = "icon_piece_splitter", model = "SM_BeltSplitter", prefab = "Piece_Splitter", price = 5,
|
||||
desc = Loc.N("Deals bundles to the belts joined to it, left, right and straight on. E makes it a sorter: one kind goes left.") },
|
||||
new PieceDef { id = PieceId.Merger, cat = PieceCat.Logistics, name = Loc.N("Merger"), icon = "icon_piece_merger", model = "SM_BeltMerger", prefab = "Piece_Merger", price = 5,
|
||||
desc = Loc.N("Brings up to three belts into one, in turn. E gives one of them the right of way.") },
|
||||
new PieceDef { id = PieceId.Square, cat = PieceCat.Structures, name = Loc.N("Square Foundation"), icon = "icon_piece_foundation", model = "SM_Foundation_Square", prefab = "Piece_Square", price = 10, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A level timber deck on mown ground. What stands on it goes along when you move it.") },
|
||||
new PieceDef { id = PieceId.Hex, cat = PieceCat.Structures, name = Loc.N("Hex Foundation"), icon = "icon_piece_hexfoundation", model = "SM_Foundation_Hex", prefab = "Piece_Hex", price = 10, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A level timber deck on mown ground, turns in steps of 30 degrees.") },
|
||||
new PieceDef { id = PieceId.Dryer, cat = PieceCat.Production, name = Loc.N("Windmill"), icon = "icon_piece_vaporizer", model = "SM_Windmill", prefab = "Piece_Dryer", price = 500, sizeX = 2, sizeZ = 2, kw = 10f,
|
||||
desc = Loc.N("Five kilos of grass become five of hay in 12 seconds. Hay pays three times as much.") },
|
||||
new PieceDef { id = PieceId.Press, cat = PieceCat.Production, name = Loc.N("Brick Press"), icon = "icon_piece_cryo", model = "SM_CryoPress", prefab = "Piece_Press", price = 1000, sizeX = 2, sizeZ = 2, kw = 18f,
|
||||
desc = Loc.N("A kilo of grass and a kilo of hay become two kilos of brick in 6 seconds. Brick pays seven times as much.") },
|
||||
new PieceDef { id = PieceId.SolarS, cat = PieceCat.Power, name = Loc.N("Solar Post"), icon = "icon_piece_solars", prefab = "Piece_SolarS", price = 75,
|
||||
desc = Loc.N("3 kW within 16 m, less when the sun is low, nothing at night.") },
|
||||
new PieceDef { id = PieceId.SolarM, cat = PieceCat.Power, name = Loc.N("Solar Pair"), icon = "icon_piece_solarm", prefab = "Piece_SolarM", price = 150, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("7.5 kW within 24 m, less when the sun is low, nothing at night.") },
|
||||
new PieceDef { id = PieceId.SolarL, cat = PieceCat.Power, name = Loc.N("Solar Tracker"), icon = "icon_piece_solarl", prefab = "Piece_SolarL", price = 300, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("16 kW within 34 m. Follows the sun, so it gives its full power all day.") },
|
||||
new PieceDef { id = PieceId.Garage, cat = PieceCat.Services, name = Loc.N("Garage"), icon = "icon_perk_fleet", model = "SM_Bld_Garage_01", prefab = "Piece_Garage", price = 200, sizeX = 9, sizeZ = 4, scale = 0.6f,
|
||||
desc = Loc.N("Sells and calls machines. What they unload on the pad goes into a silo, two ports at the back send it out as bundles.") },
|
||||
new PieceDef { id = PieceId.Binder, cat = PieceCat.Logistics, name = Loc.N("Binder"), icon = "icon_piece_binder", model = "SM_Binder", prefab = "Piece_Binder", price = 100, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("E hands it what's in your tool. It ties the grass into bundles and puts them on the belt at its front.") },
|
||||
new PieceDef { id = PieceId.RobotI, cat = PieceCat.Services, name = Loc.N("Robot Mk I"), icon = "icon_piece_robot", model = "SM_RobotDock", prefab = "Piece_RobotI", price = 250, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("Mows the 19 sectors around its dock. The dock ties what it brings into bundles for the belt.") },
|
||||
new PieceDef { id = PieceId.RobotII, cat = PieceCat.Services, name = Loc.N("Robot Mk II"), icon = "icon_piece_robot2", model = "SM_RobotDock", prefab = "Piece_RobotII", price = 500, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("37 sectors, a wider cut and a bigger hopper.") },
|
||||
new PieceDef { id = PieceId.Reaper, cat = PieceCat.Services, name = Loc.N("Reaper"), icon = "icon_piece_reaper", model = "SM_Reaper", prefab = "Piece_Reaper", price = 20000, sizeX = 3, sizeZ = 4,
|
||||
desc = Loc.N("Goes from sector to sector on its own and shoots every bundle into a Bundle Catcher, from anywhere on the planet.") },
|
||||
new PieceDef { id = PieceId.Catcher, cat = PieceCat.Services, name = Loc.N("Bundle Catcher"), icon = "icon_piece_catcher", model = "SM_BundleCatcher", prefab = "Piece_Catcher", price = 1500, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("Holds 100 kg of what Reapers shoot and puts it on the belt.") },
|
||||
new PieceDef { id = PieceId.Pole, cat = PieceCat.Power, name = Loc.N("Power Pole"), icon = "icon_piece_pole", model = "SM_Prop_Power_Pole_01", prefab = "Piece_Pole", price = 25, scale = 0.62f,
|
||||
desc = Loc.N("Carries the network 30 m further. Poles reach each other and everything around them.") },
|
||||
new PieceDef { id = PieceId.BatteryS, cat = PieceCat.Power, name = Loc.N("Battery Rack"), icon = "icon_piece_battery", model = "SM_BatteryRack", prefab = "Piece_BatteryS", price = 250, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("Stores 5 kWh of spare sun and gives it back at up to 10 kW when the panels fall short, within 12 m.") },
|
||||
new PieceDef { id = PieceId.BatteryL, cat = PieceCat.Power, name = Loc.N("Battery Bank"), icon = "icon_piece_batteryl", model = "SM_BatteryBank", prefab = "Piece_BatteryL", price = 1000, sizeX = 3, sizeZ = 2,
|
||||
desc = Loc.N("Stores 25 kWh and gives back up to 40 kW, within 16 m. A windmill and a press run all night on one.") },
|
||||
new PieceDef { id = PieceId.UnloadBay, cat = PieceCat.Logistics, name = Loc.N("Unload Bay"), icon = "icon_piece_unloadbay", model = "SM_UnloadBay", prefab = "Piece_UnloadBay", price = 150, sizeX = 4, sizeZ = 7,
|
||||
desc = Loc.N("Drive a mower onto the grate and it empties into the bin. Two hatches at the back put it on belts as bundles.") },
|
||||
new PieceDef { id = PieceId.DronePad, cat = PieceCat.Logistics, name = Loc.N("Drone Pad"), icon = "icon_piece_dronepad", model = "SM_DronePad", prefab = "Piece_DronePad", price = 600, sizeX = 3, sizeZ = 3, scale = 3.2f,
|
||||
desc = Loc.N("Its drones fly out to bundles of grass lying loose within 40 m and bring them in. The front hatch puts them on a belt. Two drones, one more per upgrade.") },
|
||||
new PieceDef { id = PieceId.Intake, cat = PieceCat.Services, company = true, name = Loc.N("Base Intake"), icon = "icon_piece_hopper", model = "SM_BaseIntake", prefab = "Piece_Intake", sizeX = 3, sizeZ = 2,
|
||||
desc = Loc.N("A low hopper against the side of the base: drop grass in or run a belt to it, and it's paid and on its way to Earth.") },
|
||||
|
||||
// structures: a 3 m grid, walls on the edges of a deck, floors and roofs on top of the walls
|
||||
new PieceDef { id = PieceId.Wall, cat = PieceCat.Structures, name = Loc.N("Wall"), icon = "icon_piece_wall", model = "SM_Wall", prefab = "Piece_Wall", price = 4, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("A 3 m timber wall. It goes on the edge of a foundation or a floor; R turns it round.") },
|
||||
new PieceDef { id = PieceId.WindowWall, cat = PieceCat.Structures, name = Loc.N("Window Wall"), icon = "icon_piece_windowwall", model = "SM_WallWindow", prefab = "Piece_WindowWall", price = 6, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("A wall with a glazed window and a flower box under it.") },
|
||||
new PieceDef { id = PieceId.DoorWall, cat = PieceCat.Structures, name = Loc.N("Door Wall"), icon = "icon_piece_doorwall", model = "SM_WallDoor", prefab = "Piece_DoorWall", price = 6, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("A wall with a doorway you can walk through, and a lantern over it.") },
|
||||
new PieceDef { id = PieceId.Railing, cat = PieceCat.Structures, name = Loc.N("Railing"), icon = "icon_piece_railing", model = "SM_Railing", prefab = "Piece_Railing", price = 2, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("Waist-high rails for the edge of a raised deck or a floor upstairs.") },
|
||||
new PieceDef { id = PieceId.Fence, cat = PieceCat.Decor, name = Loc.N("Picket Fence"), icon = "icon_piece_fence", model = "SM_Fence", prefab = "Piece_Fence", price = 1, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("Three metres of cream pickets, on the ground or on the edge of a deck.") },
|
||||
new PieceDef { id = PieceId.Floor, cat = PieceCat.Structures, name = Loc.N("Floor"), icon = "icon_piece_floor", model = "SM_Floor", prefab = "Piece_Floor", price = 6, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A storey up: it rests on the walls below. Walls and machines stand on it like on a foundation.") },
|
||||
new PieceDef { id = PieceId.FlatRoof, cat = PieceCat.Structures, name = Loc.N("Flat Roof"), icon = "icon_piece_flatroof", model = "SM_FlatRoof", prefab = "Piece_FlatRoof", price = 5, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A tin roof on top of the walls. You can stand on it, and build on it too.") },
|
||||
new PieceDef { id = PieceId.Roof, cat = PieceCat.Structures, name = Loc.N("Pitched Roof"), icon = "icon_piece_roof", model = "SM_Roof", prefab = "Piece_Roof", price = 5, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("Half of a gable roof on top of the walls, the eave on the wall you aim at. Two back to back make a whole roof.") },
|
||||
new PieceDef { id = PieceId.Stairs, cat = PieceCat.Structures, name = Loc.N("Stairs"), icon = "icon_piece_stairs", model = "SM_Stairs", prefab = "Piece_Stairs", price = 8, sizeX = 1, sizeZ = 3,
|
||||
desc = Loc.N("A flight up one storey, 3 m. It climbs the way the arrow points.") },
|
||||
new PieceDef { id = PieceId.Steps, cat = PieceCat.Structures, name = Loc.N("Steps"), icon = "icon_piece_steps", model = "SM_Steps", prefab = "Piece_Steps", price = 4, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("Six wide steps up to a raised foundation, 1.5 m high.") },
|
||||
new PieceDef { id = PieceId.Pillar, cat = PieceCat.Structures, name = Loc.N("Pillar"), icon = "icon_piece_pillar", model = "SM_Pillar", prefab = "Piece_Pillar", price = 2, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("A 3 m timber post on a stone base: it holds up a floor where there's no wall.") },
|
||||
new PieceDef { id = PieceId.Planter, cat = PieceCat.Decor, name = Loc.N("Flower Box"), icon = "icon_piece_planter", model = "SM_Planter", prefab = "Piece_Planter", price = 3, sizeX = 2, sizeZ = 1,
|
||||
desc = Loc.N("Flowers in a timber box. They don't pay, they just look nice.") },
|
||||
new PieceDef { id = PieceId.Lamppost, cat = PieceCat.Decor, name = Loc.N("Lamp Post"), icon = "icon_piece_lamppost", model = "SM_Lamppost", prefab = "Piece_Lamppost", price = 4, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("A farm lamp that comes on at dusk.") },
|
||||
new PieceDef { id = PieceId.Bench, cat = PieceCat.Decor, name = Loc.N("Bench"), icon = "icon_piece_bench", model = "SM_Bench", prefab = "Piece_Bench", price = 3, sizeX = 2, sizeZ = 1,
|
||||
desc = Loc.N("Somewhere to sit and watch the robots work.") },
|
||||
new PieceDef { id = PieceId.Crates, cat = PieceCat.Decor, name = Loc.N("Crates"), icon = "icon_piece_crates", model = "SM_Crate", prefab = "Piece_Crates", price = 2, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("Company crates, stacked two high.") },
|
||||
new PieceDef { id = PieceId.Flagpole, cat = PieceCat.Decor, name = Loc.N("Flagpole"), icon = "icon_piece_flagpole", model = "SM_Flagpole", prefab = "Piece_Flagpole", price = 5, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("The crew's own flag, four metres up.") },
|
||||
};
|
||||
|
||||
public static PieceDef Piece(PieceId id) => Pieces[(int)id];
|
||||
|
||||
// ───────────────────────── piece upgrades ─────────────────────────
|
||||
|
||||
public const int MaxTier = 3;
|
||||
public static string TierName(int t) => Loc.F("Mk {0}", t == 0 ? "I" : t == 1 ? "II" : t == 2 ? "III" : "IV");
|
||||
|
||||
public static UpgradeKind UpgradeOf(PieceId id)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case PieceId.Belt: case PieceId.Splitter: case PieceId.Merger: return UpgradeKind.Belt;
|
||||
case PieceId.Dryer: case PieceId.Press: case PieceId.Binder: return UpgradeKind.Machine;
|
||||
case PieceId.RobotI: case PieceId.RobotII: case PieceId.Reaper: return UpgradeKind.Robot;
|
||||
case PieceId.Garage: case PieceId.UnloadBay: case PieceId.Catcher: case PieceId.DronePad: return UpgradeKind.Silo;
|
||||
default: return UpgradeKind.None;
|
||||
}
|
||||
}
|
||||
|
||||
static readonly float[] BeltTiers = { 1f, 1.5f, 2f, 3f }, MachineTiers = { 1f, 1.5f, 2f, 2.5f }, RobotTiers = { 1f, 1.3f, 1.6f, 1.9f }, SiloTiers = { 1f, 2f, 3f, 4f };
|
||||
|
||||
public static float TierMul(UpgradeKind k, int tier)
|
||||
{
|
||||
tier = Mathf.Clamp(tier, 0, MaxTier);
|
||||
switch (k)
|
||||
{
|
||||
case UpgradeKind.Belt: return BeltTiers[tier];
|
||||
case UpgradeKind.Machine: return MachineTiers[tier];
|
||||
case UpgradeKind.Robot: return RobotTiers[tier];
|
||||
case UpgradeKind.Silo: return SiloTiers[tier];
|
||||
default: return 1f;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A machine at a higher tier also draws more power.</summary>
|
||||
public static float TierPower(int tier) => 1f + 0.25f * Mathf.Clamp(tier, 0, MaxTier);
|
||||
|
||||
public static string TierEffect(UpgradeKind k, int tier)
|
||||
{
|
||||
float m = TierMul(k, tier);
|
||||
switch (k)
|
||||
{
|
||||
case UpgradeKind.Belt: return Loc.F("runs at x{0:0.#} speed", m);
|
||||
case UpgradeKind.Machine: return Loc.F("works x{0:0.#} as fast, draws x{1:0.##} power", m, TierPower(tier));
|
||||
case UpgradeKind.Robot: return Loc.F("x{0:0.#} speed and hopper", m);
|
||||
case UpgradeKind.Silo: return Loc.F("sends out x{0:0} the bundles", m);
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static double UpgradePrice(BuildPiece p, int tier)
|
||||
{
|
||||
double basis = p.Run ? Math.Max(20d, p.Run.Metres * 4d) : Math.Max(20d, p.Def.price);
|
||||
return Math.Round(basis * (tier == 0 ? 0.5 : tier == 1 ? 1.2 : 2.5));
|
||||
}
|
||||
public static bool IsFoundation(PieceId id) => id == PieceId.Square || id == PieceId.Hex;
|
||||
/// <summary>Something to stand and build on: a foundation on the ground, or a floor or flat roof a storey up.</summary>
|
||||
public static bool IsDeck(PieceId id) => IsFoundation(id) || id == PieceId.Floor || id == PieceId.FlatRoof;
|
||||
/// <summary>A deck with four 3 m edges, where walls go.</summary>
|
||||
public static bool IsSquareDeck(PieceId id) => id == PieceId.Square || id == PieceId.Floor || id == PieceId.FlatRoof;
|
||||
/// <summary>A storey: walls are this tall, and a floor on them is this far above the deck they stand on.</summary>
|
||||
public const float Storey = 3f;
|
||||
|
||||
public static Fit FitOf(PieceId id)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case PieceId.Wall: case PieceId.WindowWall: case PieceId.DoorWall: case PieceId.Railing: case PieceId.Fence: return Fit.Edge;
|
||||
case PieceId.Floor: case PieceId.FlatRoof: case PieceId.Roof: return Fit.Top;
|
||||
default: return Fit.Free;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A wall-high piece: a floor or a roof can rest on it.</summary>
|
||||
public static bool Holds(PieceId id) => id == PieceId.Wall || id == PieceId.WindowWall || id == PieceId.DoorWall || id == PieceId.Pillar;
|
||||
public static bool IsPanel(PieceId id) => id >= PieceId.SolarS && id <= PieceId.SolarL;
|
||||
|
||||
static readonly RecipeDef Drying = new RecipeDef { grass = 5f, seconds = 12f, makes = 5f, product = CargoKind.Hay };
|
||||
static readonly RecipeDef Pressing = new RecipeDef { grass = 1f, hay = 1f, seconds = 6f, makes = 2f, product = CargoKind.Brick };
|
||||
public static RecipeDef Recipe(PieceId id) => id == PieceId.Press ? Pressing : Drying;
|
||||
|
||||
static readonly PanelDef Post = new PanelDef { kw = 3f, radius = 16f };
|
||||
static readonly PanelDef Pair = new PanelDef { kw = 7.5f, radius = 24f };
|
||||
static readonly PanelDef Tracker = new PanelDef { kw = 16f, radius = 34f, tracker = true };
|
||||
public static PanelDef Panel(PieceId id) => id == PieceId.SolarL ? Tracker : id == PieceId.SolarM ? Pair : Post;
|
||||
|
||||
static readonly BatteryDef Rack = new BatteryDef { kwh = 5f, kw = 10f, radius = 12f };
|
||||
static readonly BatteryDef Bank = new BatteryDef { kwh = 25f, kw = 40f, radius = 16f };
|
||||
public static BatteryDef Battery(PieceId id) => id == PieceId.BatteryL ? Bank : Rack;
|
||||
public static bool IsBattery(PieceId id) => id == PieceId.BatteryS || id == PieceId.BatteryL;
|
||||
|
||||
public const float PoleReach = 30f, PoleHeight = 3.05f, PoleArm = 0.62f;
|
||||
|
||||
/// <summary>How far a power piece reaches, 0 for anything else.</summary>
|
||||
public static float Reach(PieceId id) => IsPanel(id) ? Panel(id).radius : IsBattery(id) ? Battery(id).radius : id == PieceId.Pole ? PoleReach : 0f;
|
||||
|
||||
/// <summary>Seconds from noon to noon. The original's figure isn't known.</summary>
|
||||
public const float DayLength = 1800f;
|
||||
|
||||
// ───────────────────────── economy (shared by server & client prediction) ─────────────────────────
|
||||
|
||||
public static float BinMul(int level) => 1 << Mathf.Clamp(level, 0, 3);
|
||||
public static float CompactorMul(int level) => 1f + level * 0.15f;
|
||||
public static float ToolCap(ToolId t, int binLevel, int compactor) => Tool(t).capacity * BinMul(binLevel) * CompactorMul(compactor);
|
||||
|
||||
public static float WidthBonus(int level) => level * 0.08f;
|
||||
public const float ToolReach = 2.6f;
|
||||
public const float BundleKg = 1f;
|
||||
public static float BundleSeconds(int quick, int express) =>
|
||||
0.6f * (quick switch { 0 => 1f, 1 => 0.75f, 2 => 0.56f, _ => 0.42f }) * (express > 0 ? 0.5f : 1f);
|
||||
|
||||
public static float MoveMul(int stride, int frame) => (1f + stride * 0.07f) * (frame > 0 ? 1.08f : 1f);
|
||||
public static float JumpMul(int leap, int frame) => (1f + leap * 0.2f) * (frame > 0 ? 1.15f : 1f);
|
||||
public static float ThrowMul(int level) => 1f + level * 0.25f;
|
||||
public static float PayoutMul(int prices, int exchange) => (1f + prices * 0.06f) * (exchange > 0 ? 1.1f : 1f);
|
||||
public static float ToolPriceMul(int deals) => 1f - deals * 0.05f;
|
||||
|
||||
// cargo
|
||||
public static string CargoName(CargoKind k) => k switch { CargoKind.Hay => Loc.T("Hay"), CargoKind.Brick => Loc.T("Pressed Brick"), _ => Loc.T("Grass Bundle") };
|
||||
/// <summary>What Earth pays per kilo for each form (before market bonuses).</summary>
|
||||
public static float PerKg(CargoKind k) => k switch { CargoKind.Hay => 3f, CargoKind.Brick => 7f, _ => 1f };
|
||||
|
||||
// belts
|
||||
public const float BeltSpeed = 2.2f;
|
||||
public const float BeltShortest = 0.8f, BeltLongest = 30f, BeltLowest = 0.4f, BeltHighest = 6f, BeltSteepest = 40f;
|
||||
public static double BeltPrice(float metres) => System.Math.Round(metres * Piece(PieceId.Belt).price, 2);
|
||||
|
||||
// vehicles
|
||||
public const double TravelPrice = 50d;
|
||||
|
||||
public static readonly RobotDef[] Robots =
|
||||
{
|
||||
new RobotDef { piece = PieceId.RobotI, name = Loc.N("Robot Mk I"), reach = 2, width = 0.9f, speed = 1.6f, hopper = 20f },
|
||||
new RobotDef { piece = PieceId.RobotII, name = Loc.N("Robot Mk II"), reach = 3, width = 1.2f, speed = 2.2f, hopper = 50f },
|
||||
new RobotDef { piece = PieceId.Reaper, name = Loc.N("Reaper"), width = 1.8f, speed = 3f, hopper = 40f },
|
||||
};
|
||||
|
||||
public static RobotDef Robot(PieceId id)
|
||||
{
|
||||
foreach (var r in Robots) if (r.piece == id) return r;
|
||||
return Robots[0];
|
||||
}
|
||||
|
||||
public static readonly VehicleDef[] Vehicles =
|
||||
{
|
||||
new VehicleDef { kind = VehicleKind.Push, name = Loc.N("Push Mower"), icon = "icon_vehicle_push", price = 300, width = 1.35f, hopper = 100f, speed = 5f, accel = 7f, turn = 3f,
|
||||
desc = Loc.N("The first step up from a scythe: a wide strip at walking pace.") },
|
||||
new VehicleDef { kind = VehicleKind.Rider, name = Loc.N("Garden Rider"), icon = "icon_vehicle_ski", price = 1000, width = 2f, hopper = 500f, speed = 9.7f, accel = 11f, turn = 2.2f,
|
||||
desc = Loc.N("Sit down, drive, mow. Unloads at a garage pad.") },
|
||||
new VehicleDef { kind = VehicleKind.Pickup, name = Loc.N("Pickup"), icon = "icon_vehicle_hover", price = 2000, speed = 14f, accel = 10f, turn = 1.8f, bed = 4, seatDrop = 0.56f, seatAhead = 0.12f,
|
||||
desc = Loc.N("Doesn't mow. Fast, and carries four bundles: E loads the one in your arms, T tips them out.") },
|
||||
new VehicleDef { kind = VehicleKind.Tractor, name = Loc.N("Mowing Tractor"), icon = "icon_vehicle_tug", price = 2500, width = 2.8f, hopper = 1200f, speed = 9f, accel = 8f, turn = 1.5f, seatDrop = 0.42f,
|
||||
desc = Loc.N("A proper machine for proper fields.") },
|
||||
new VehicleDef { kind = VehicleKind.Combine, name = Loc.N("Combine"), icon = "icon_vehicle_combine", price = 6000, width = 3.7f, hopper = 3000f, speed = 8f, accel = 5f, turn = 1.3f, seatDrop = 0.45f,
|
||||
desc = Loc.N("Slow to turn, and nothing else cuts as wide or carries as much.") },
|
||||
new VehicleDef { kind = VehicleKind.Hauler, name = Loc.N("Haul Tractor"), icon = "icon_vehicle_hauler", price = 4000, width = 1.6f, hopper = 4000f, speed = 12f, accel = 8f, turn = 1.4f, seatDrop = 0.18f,
|
||||
desc = Loc.N("A narrow cutter and a huge tank on a trailer: mow far out, come back once.") },
|
||||
new VehicleDef { kind = VehicleKind.Mulcher, name = Loc.N("Wide Mulcher"), icon = "icon_vehicle_mulcher", price = 8000, width = 5.5f, hopper = 900f, speed = 7f, accel = 5f, turn = 1.1f, seatDrop = 0.18f,
|
||||
desc = Loc.N("Wings out to five and a half metres. Fills fast: put an Unload Bay near the field.") },
|
||||
new VehicleDef { kind = VehicleKind.Baler, name = Loc.N("Baler Tractor"), icon = "icon_vehicle_baler", price = 3500, width = 2.2f, hopper = 600f, speed = 9f, accel = 8f, turn = 1.5f, bales = true,
|
||||
desc = Loc.N("Bales as it goes: pull up beside the start of any belt and its chute feeds the belt, five bundles a second.") },
|
||||
};
|
||||
|
||||
public static VehicleDef Vehicle(VehicleKind k) => Vehicles[(int)k];
|
||||
|
||||
public static readonly TuneDef[] Tunes =
|
||||
{
|
||||
new TuneDef { id = TuneId.Motors, name = Loc.N("Tuned Motors"), prices = new long[] { 250, 600, 1500 }, effect = l => Loc.F("+{0}% speed and pull", l * 10) },
|
||||
new TuneDef { id = TuneId.Hopper, name = Loc.N("Big Hopper"), prices = new long[] { 200, 500, 1200 }, effect = l => Loc.F("+{0}% hopper", l * 30) },
|
||||
new TuneDef { id = TuneId.Turbo, name = Loc.N("Turbo Kit"), prices = new long[] { 400, 1200 }, effect = l => Loc.F("SHIFT boost {0:0}%", BoostMul(l) * 100f) },
|
||||
new TuneDef { id = TuneId.Cruise, name = Loc.N("Cruise Control"), prices = new long[] { 500 }, effect = l => Loc.T("C holds your speed") },
|
||||
new TuneDef { id = TuneId.Cutter, name = Loc.N("Cutter Control"), prices = new long[] { 400, 900, 2000 }, effect = l => Loc.F("Strip +{0}% at {1:0}% speed", l * 25, CutterSpeed(l) * 100f) },
|
||||
new TuneDef { id = TuneId.Release, name = Loc.N("Quick Release"), prices = new long[] { 150, 400 }, effect = l => Loc.F("+{0}% unloading", l * 50) },
|
||||
new TuneDef { id = TuneId.Lights, name = Loc.N("Floodlights"), prices = new long[] { 100, 300 }, effect = l => Loc.F("+{0}% light at night", l * 60) },
|
||||
};
|
||||
|
||||
public static TuneDef Tune(TuneId t) => Tunes[(int)t];
|
||||
/// <summary>Upgrades cost more on dearer machines, from half to three times the listed price.</summary>
|
||||
public static double TunePrice(VehicleKind k, TuneId t, int level) => System.Math.Round(Tune(t).prices[level] * System.Math.Min(3d, System.Math.Max(0.5d, Vehicle(k).price / 1000d)), 2);
|
||||
public static bool TuneFits(VehicleKind k, TuneId t) => Vehicle(k).bed == 0 || (t != TuneId.Hopper && t != TuneId.Cutter && t != TuneId.Release);
|
||||
public static float BoostMul(int level) => level >= 2 ? 1.65f : level == 1 ? 1.5f : 1.25f;
|
||||
public static float CutterSpeed(int level) => level >= 3 ? 0.6f : level == 2 ? 0.72f : level == 1 ? 0.85f : 1f;
|
||||
public static float VehicleTankMul(int level) => 1f + level * 0.3f;
|
||||
public static float VehicleSpeedMul(int level) => 1f + level * 0.1f;
|
||||
public static float DockRate(int level) => 120f * (1f + level * 0.5f);
|
||||
|
||||
public static string ToRoman(int n) => n switch { 1 => "I", 2 => "II", 3 => "III", 4 => "IV", 5 => "V", _ => n.ToString() };
|
||||
|
||||
public static string Kilos(double kg)
|
||||
{
|
||||
if (kg >= 1_000_000) return Loc.F("{0} t", Loc.Num(kg / 1000d, "N0"));
|
||||
if (kg >= 10_000) return Loc.F("{0} t", Loc.Num(kg / 1000d, "0.#"));
|
||||
return Loc.F("{0} kg", Loc.Num(kg, kg < 100d ? "0.##" : "N0"));
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/GameDefs.cs.meta
Normal file
2
Assets/Scripts/Gameplay/GameDefs.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0cbdb0f35d4c2984fa886594181b5501
|
||||
60
Assets/Scripts/Gameplay/Garage.cs
Normal file
60
Assets/Scripts/Gameplay/Garage.cs
Normal file
@ -0,0 +1,60 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A garage you build yourself: sells and calls machines like the one at the base, and whatever a machine unloads on the pad
|
||||
/// in front goes into its silo. Two ports at the back turn the silo into bundles for the belts.
|
||||
/// </summary>
|
||||
public class Garage : SiloPiece
|
||||
{
|
||||
public static readonly List<Garage> All = new List<Garage>();
|
||||
|
||||
// the garage stands at 0.6 times the pack model (half what it was: it towered over the base): its front is 1.9 m out,
|
||||
// its back wall 1.9 m back. The pad is still sized for the machines.
|
||||
const float PadFront = 2.4f, PadLong = 11f, PadWide = 6.5f, PortBack = 2.24f;
|
||||
|
||||
public override string Prompt => Loc.F("Garage — buy, call & upgrade machines (silo {0})", GameDefs.Kilos(Silo.Value));
|
||||
|
||||
public override void Interact()
|
||||
{
|
||||
Sfx.Play("ui_open");
|
||||
UIRoot.I?.OpenGarage(this);
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn() { All.Add(this); base.OnNetworkSpawn(); }
|
||||
public override void OnNetworkDespawn() { All.Remove(this); base.OnNetworkDespawn(); }
|
||||
|
||||
public override string PadName => Loc.T("Garage pad");
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
var back = -transform.forward;
|
||||
var at = transform.position + transform.up * GameDefs.BeltLowest + back * PortBack;
|
||||
into.Add(new Port { at = at - transform.right * 0.8f, dir = back });
|
||||
into.Add(new Port { at = at + transform.right * 0.8f, dir = back });
|
||||
}
|
||||
|
||||
/// <summary>Where a called machine appears: the middle of the pad.</summary>
|
||||
public override Vector3 PadSpot => transform.position + transform.forward * (PadFront + PadLong * 0.5f) + transform.up * 0.6f;
|
||||
|
||||
public override bool OnPad(Vector3 p)
|
||||
{
|
||||
var l = transform.InverseTransformPoint(p);
|
||||
return Mathf.Abs(l.x) < PadWide && l.z > PadFront - 1f && l.z < PadFront + PadLong && Mathf.Abs(l.y) < 4f;
|
||||
}
|
||||
|
||||
public static Garage Under(Vector3 p)
|
||||
{
|
||||
foreach (var g in All) if (g && g.OnPad(p)) return g;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Garage.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Garage.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0ac65e3a49c10724ea8bdcaf15a12b76
|
||||
210
Assets/Scripts/Gameplay/Grabbable.cs
Normal file
210
Assets/Scripts/Gameplay/Grabbable.cs
Normal file
@ -0,0 +1,210 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Grabbable.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Grabbable.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 50acd62fb7dd3264c9789ce552d296d9
|
||||
13
Assets/Scripts/Gameplay/IInteractable.cs
Normal file
13
Assets/Scripts/Gameplay/IInteractable.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public interface IInteractable
|
||||
{
|
||||
string Prompt { get; }
|
||||
bool CanInteract { get; }
|
||||
void Interact();
|
||||
}
|
||||
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/IInteractable.cs.meta
Normal file
2
Assets/Scripts/Gameplay/IInteractable.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 877ba4cdd9f1ba343a81ec12b5dbb728
|
||||
47
Assets/Scripts/Gameplay/Junction.cs
Normal file
47
Assets/Scripts/Gameplay/Junction.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A belt piece with a choice to make: the modes it can switch between.</summary>
|
||||
public interface IJunction
|
||||
{
|
||||
int ModeCount { get; }
|
||||
string ModeName(int mode);
|
||||
Color ModeColor(int mode);
|
||||
}
|
||||
|
||||
/// <summary>E on a splitter or a merger switches what it does, and the little sign on it shows which.</summary>
|
||||
public class Junction : MonoBehaviour, IInteractable
|
||||
{
|
||||
public Renderer sign;
|
||||
|
||||
BuildPiece _piece;
|
||||
IJunction _junction;
|
||||
MaterialPropertyBlock _mpb;
|
||||
int _shown = -1;
|
||||
static readonly int BaseColor = Shader.PropertyToID("_BaseColor");
|
||||
|
||||
BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
IJunction Parts => _junction ?? (_junction = GetComponentInChildren<IJunction>());
|
||||
|
||||
public string Prompt => Loc.F("{0}: {1} (E changes it)", Piece.Def.name, Parts.ModeName(Piece.Mode.Value));
|
||||
public bool CanInteract => true;
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
Piece.NextModeRpc(Parts.ModeCount);
|
||||
Sfx.Play("ui_click", 0.7f);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
int mode = Piece.Mode.Value;
|
||||
if (mode == _shown || !sign) return;
|
||||
_shown = mode;
|
||||
if (_mpb == null) _mpb = new MaterialPropertyBlock();
|
||||
sign.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(BaseColor, Parts.ModeColor(mode));
|
||||
sign.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Junction.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Junction.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b8dce3ea7ba192843a6c27a35253cdb1
|
||||
43
Assets/Scripts/Gameplay/Lamppost.cs
Normal file
43
Assets/Scripts/Gameplay/Lamppost.cs
Normal file
@ -0,0 +1,43 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A lamp post that comes on as the light goes: its glass glows and it throws a warm pool round its foot.</summary>
|
||||
public class Lamppost : MonoBehaviour
|
||||
{
|
||||
public Renderer glow;
|
||||
Light _light;
|
||||
MaterialPropertyBlock _mpb;
|
||||
float _on = -1f;
|
||||
static readonly int EmissionId = Shader.PropertyToID("_EmissionColor"), BaseId = Shader.PropertyToID("_BaseColor");
|
||||
static readonly Color Warm = new Color(1f, 0.78f, 0.45f);
|
||||
|
||||
void Start()
|
||||
{
|
||||
var go = new GameObject("Light");
|
||||
go.transform.SetParent(transform, false);
|
||||
go.transform.localPosition = new Vector3(0f, 2.35f, 0f);
|
||||
_light = go.AddComponent<Light>();
|
||||
_light.type = LightType.Point;
|
||||
_light.color = Warm;
|
||||
_light.range = 9f;
|
||||
_light.shadows = LightShadows.None;
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
// lit a little before it's properly dark, out a little after the sun is up
|
||||
float on = Mathf.Clamp01(DayNight.Dark * 1.6f + DayNight.Dusk * 0.6f);
|
||||
if (Mathf.Abs(on - _on) < 0.02f) return;
|
||||
_on = on;
|
||||
_light.enabled = on > 0.05f;
|
||||
_light.intensity = on * 2.2f;
|
||||
if (!glow) return;
|
||||
glow.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(EmissionId, Warm * (0.2f + on * 3f));
|
||||
_mpb.SetColor(BaseId, Color.Lerp(new Color(0.85f, 0.82f, 0.7f), Warm, on));
|
||||
glow.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Lamppost.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Lamppost.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6558f3088100a79438c30d74e7912470
|
||||
194
Assets/Scripts/Gameplay/Machine.cs
Normal file
194
Assets/Scripts/Gameplay/Machine.cs
Normal file
@ -0,0 +1,194 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A built thing that remembers more than where it stands: what's inside, how full its battery is.</summary>
|
||||
public interface IPieceState
|
||||
{
|
||||
float[] State { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dryer and the brick press: cargo comes in by belt or by hand and turns into the product all the time, not in
|
||||
/// batches, at the speed the power allows: 100% power is full speed, 30% is a third of it. What's made goes onto the belt at
|
||||
/// the front, or onto the ground if there's none.
|
||||
/// </summary>
|
||||
public class Machine : NetworkBehaviour, ICargoSink, IPorts, IInteractable, IPieceState
|
||||
{
|
||||
public static readonly List<Machine> All = new List<Machine>();
|
||||
|
||||
/// <summary>A hopper holds this many kilos of each thing.</summary>
|
||||
const float Hold = 10f;
|
||||
const float PortOut = 1.05f;
|
||||
|
||||
public readonly NetworkVariable<float> Grass = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Hay = new NetworkVariable<float>();
|
||||
/// <summary>Kilos made and waiting to leave.</summary>
|
||||
public readonly NetworkVariable<float> Made = new NetworkVariable<float>();
|
||||
/// <summary>Share of the power it asks for that it's getting, 0..1: that's how fast it runs.</summary>
|
||||
public readonly NetworkVariable<float> Power = new NetworkVariable<float>();
|
||||
|
||||
public Renderer lamp;
|
||||
public Transform spin;
|
||||
|
||||
BuildPiece _piece;
|
||||
float _done, _nextEject, _pace, _spun, _nextThump;
|
||||
bool _short;
|
||||
int _spinAxis = -1;
|
||||
AudioSource _hum;
|
||||
MaterialPropertyBlock _mpb;
|
||||
static readonly int Emission = Shader.PropertyToID("_EmissionColor");
|
||||
readonly List<Port> _ports = new List<Port>();
|
||||
|
||||
BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
RecipeDef Recipe => GameDefs.Recipe(Piece.piece);
|
||||
public float Kw => Piece.Def.kw * GameDefs.TierPower(Piece.Tier.Value);
|
||||
|
||||
const float Crumb = 0.001f;
|
||||
|
||||
bool Stocked => Grass.Value > Crumb && (Recipe.hay <= 0f || Hay.Value > Crumb);
|
||||
/// <summary>Does it want power right now?</summary>
|
||||
public bool Busy => Stocked && Made.Value < Hold;
|
||||
/// <summary>Kilos a minute it's turning out right now.</summary>
|
||||
public float PerMinute => Busy ? 60f * Recipe.makes / Recipe.seconds * Power.Value : 0f;
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
_hum = Sfx.Loop("machine_hum_loop", transform, 0f);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
if (_hum) Destroy(_hum.gameObject);
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public float[] State
|
||||
{
|
||||
get => new[] { Grass.Value, Hay.Value, Made.Value };
|
||||
set
|
||||
{
|
||||
if (value == null || value.Length < 3) return;
|
||||
Grass.Value = value[0];
|
||||
Hay.Value = value[1];
|
||||
Made.Value = value[2];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>In at the back, out at the front. The press has two ways in and either takes either.</summary>
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
var f = transform.forward;
|
||||
var r = transform.right;
|
||||
var at = transform.position + transform.up * GameDefs.BeltLowest;
|
||||
if (Recipe.hay > 0f)
|
||||
{
|
||||
into.Add(new Port { at = at - f * PortOut - r * 0.5f, dir = f, input = true });
|
||||
into.Add(new Port { at = at - f * PortOut + r * 0.5f, dir = f, input = true });
|
||||
}
|
||||
else into.Add(new Port { at = at - f * PortOut, dir = f, input = true });
|
||||
into.Add(new Port { at = at + f * PortOut, dir = f });
|
||||
}
|
||||
|
||||
public string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
var r = Recipe;
|
||||
string have = r.hay > 0f ? Loc.F("{0} grass, {1} hay", GameDefs.Kilos(Grass.Value), GameDefs.Kilos(Hay.Value)) : Loc.F("{0} grass", GameDefs.Kilos(Grass.Value));
|
||||
string state = !Busy ? (Made.Value >= Hold ? Loc.T("the way out is blocked") : Loc.T("waiting for grass")) : Power.Value <= 0f ? Loc.T("no power") : Loc.F("running at {0:0}% speed, {1:0.#} kg a minute", Power.Value * 100f, PerMinute);
|
||||
return Loc.F("{0}: {1}, {2}", Piece.Def.name, have, state);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanInteract => false;
|
||||
public void Interact() { }
|
||||
|
||||
public bool ServerAccept(Cargo c, Vector3 from, Vector3 dir)
|
||||
{
|
||||
if (!c || !c.IsSpawned) return false;
|
||||
float kg = c.Kg.Value;
|
||||
var r = Recipe;
|
||||
if (c.kind == CargoKind.Grass && r.grass > 0f && Grass.Value + kg <= Hold) Grass.Value += kg;
|
||||
else if (c.kind == CargoKind.Hay && r.hay > 0f && Hay.Value + kg <= Hold) Hay.Value += kg;
|
||||
else return false;
|
||||
c.Grab.Consumed = true;
|
||||
c.NetworkObject.Despawn(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!IsSpawned) return;
|
||||
Visuals();
|
||||
if (!IsServer) return;
|
||||
Eject();
|
||||
if (!Busy) return;
|
||||
var r = Recipe;
|
||||
// it adds up for a moment so the network isn't written to every frame
|
||||
if (Piece.Switched) return;
|
||||
_done += Time.deltaTime * Power.Value * Piece.TierMul / r.seconds;
|
||||
if (_done < 0.02f) return;
|
||||
float take = Mathf.Min(_done, Grass.Value / r.grass, (Hold - Made.Value) / r.makes);
|
||||
if (r.hay > 0f) take = Mathf.Min(take, Hay.Value / r.hay);
|
||||
_done = 0f;
|
||||
Grass.Value = Mathf.Max(0f, Grass.Value - r.grass * take);
|
||||
Hay.Value = Mathf.Max(0f, Hay.Value - r.hay * take);
|
||||
Made.Value += r.makes * take;
|
||||
}
|
||||
|
||||
/// <summary>On every peer: the lamp, the moving part and the sound all follow the speed it's running at.</summary>
|
||||
void Visuals()
|
||||
{
|
||||
_pace = Mathf.MoveTowards(_pace, Busy ? Power.Value : 0f, Time.deltaTime * 1.5f);
|
||||
if (_hum)
|
||||
{
|
||||
_hum.volume = _pace * 0.32f * Sfx.SfxVolume;
|
||||
_hum.pitch = Mathf.Lerp(0.6f, 1.1f, _pace);
|
||||
}
|
||||
// the press comes down slower the less power it gets
|
||||
if (Piece.piece == PieceId.Press && _pace > 0.05f && Time.time >= _nextThump)
|
||||
{
|
||||
_nextThump = Time.time + 2.2f / _pace;
|
||||
Sfx.PlayAt("press_thump", transform.position + transform.up, 0.45f);
|
||||
}
|
||||
bool slow = Busy && Power.Value < 0.5f;
|
||||
if (slow && !_short) Sfx.PlayAt("power_low", transform.position + transform.up, 0.4f, 1f, 0f, 20f);
|
||||
_short = slow;
|
||||
if (spin)
|
||||
{
|
||||
if (_spinAxis < 0) _spinAxis = BaseRot.LocalAxisFor(spin, transform.forward);
|
||||
_spun += _pace * 300f * Time.deltaTime;
|
||||
var axis = _spinAxis == 0 ? Vector3.right : _spinAxis == 1 ? Vector3.up : Vector3.forward;
|
||||
spin.localRotation = BaseRot.Of(spin) * Quaternion.Euler(axis * _spun);
|
||||
}
|
||||
if (lamp)
|
||||
{
|
||||
var c = !Busy ? new Color(0.12f, 0.2f, 0.12f) : Power.Value <= 0f ? new Color(1f, 0.1f, 0.08f) : Power.Value < 0.99f ? new Color(1f, 0.7f, 0.1f) : new Color(0.2f, 1f, 0.3f);
|
||||
lamp.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(Emission, c * 2.2f);
|
||||
lamp.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One kilo at a time through the front, onto whatever takes it.</summary>
|
||||
void Eject()
|
||||
{
|
||||
if (Made.Value < 1f || Time.time < _nextEject) return;
|
||||
_nextEject = Time.time + 0.3f;
|
||||
_ports.Clear();
|
||||
Ports(_ports);
|
||||
if (BeltNet.Send(Piece, _ports[_ports.Count - 1], Recipe.product)) Made.Value -= 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Machine.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Machine.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0c4e72debb52c37409daabb7f5983fc0
|
||||
394
Assets/Scripts/Gameplay/Mowbot.cs
Normal file
394
Assets/Scripts/Gameplay/Mowbot.cs
Normal file
@ -0,0 +1,394 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public enum RobotMood : byte { Mowing, Travelling, Unloading, Waiting, Finished, NoCatcher }
|
||||
|
||||
/// <summary>
|
||||
/// A mower that drives itself. Only the server decides where it goes: it takes the nearest sector it may work and nobody else
|
||||
/// has, walks it row by row and says where it is five times a second. Every peer cuts what it hears, so the grass goes for all.
|
||||
/// </summary>
|
||||
public abstract class Mowbot : NetworkBehaviour, IInteractable, IPieceState
|
||||
{
|
||||
public static readonly List<Mowbot> All = new List<Mowbot>();
|
||||
/// <summary>The demo's fast forward, on the server.</summary>
|
||||
public static float Haste = 1f;
|
||||
|
||||
const float Tick = 0.2f, Overrun = 0.6f, IdleWait = 5f;
|
||||
const float EngineVolume = 0.16f;
|
||||
const int SearchLimit = 4000;
|
||||
|
||||
public readonly NetworkVariable<Vector3> At = new NetworkVariable<Vector3>();
|
||||
public readonly NetworkVariable<bool> Mowing = new NetworkVariable<bool>();
|
||||
public readonly NetworkVariable<float> Hopper = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<byte> Mood = new NetworkVariable<byte>();
|
||||
|
||||
static readonly Dictionary<int, Mowbot> s_held = new Dictionary<int, Mowbot>();
|
||||
static readonly Queue<(int id, int ring)> s_queue = new Queue<(int, int)>();
|
||||
static readonly HashSet<int> s_seen = new HashSet<int>();
|
||||
static readonly List<Vector3> s_rows = new List<Vector3>();
|
||||
|
||||
readonly List<Vector3> _way = new List<Vector3>();
|
||||
readonly HashSet<int> _empty = new HashSet<int>();
|
||||
int _next, _sector = -1;
|
||||
bool _travel;
|
||||
float _clock, _idleUntil;
|
||||
// the body runs from where it was to the latest tick's spot at an even pace over one tick
|
||||
Vector3 _shown, _from, _to;
|
||||
float _leg = 1f;
|
||||
RobotDef _def;
|
||||
|
||||
/// <summary>Where the body is drawn, smooth between the ticks that move At.</summary>
|
||||
public Vector3 Shown => _shown;
|
||||
/// <summary>For the test bots: how the body stands, as the eye sees it.</summary>
|
||||
public Transform ShownBody => Body;
|
||||
AudioSource _engine;
|
||||
|
||||
protected Vector3 Dir;
|
||||
protected bool Homing;
|
||||
|
||||
public RobotDef Def => _def ?? (_def = GameDefs.Robot(GetComponent<BuildPiece>().piece));
|
||||
BuildPiece _bp;
|
||||
/// <summary>The dock's upgrade level makes the robot faster and its hopper bigger.</summary>
|
||||
protected float Boost => (_bp ? _bp : (_bp = GetComponent<BuildPiece>())) ? _bp.TierMul : 1f;
|
||||
public float HopperCap => Def.hopper * Boost;
|
||||
public RobotMood Doing => (RobotMood)Mood.Value;
|
||||
|
||||
protected abstract Transform Body { get; }
|
||||
|
||||
/// <summary>The body's model has its nose on local -Z, so it is turned the other way round to go nose first.</summary>
|
||||
protected virtual bool NoseOnBack => false;
|
||||
protected abstract Vector3 Origin { get; }
|
||||
protected abstract int Reach { get; }
|
||||
protected virtual Vector3 HomeDir => Dir;
|
||||
/// <summary>Unloading, or out of room: true keeps it where it is for this tick.</summary>
|
||||
protected abstract bool Stay(float dt);
|
||||
protected virtual void Arrived() { }
|
||||
protected abstract void NoWork();
|
||||
|
||||
public abstract string Prompt { get; }
|
||||
public bool CanInteract => true;
|
||||
public void Interact() => Sfx.Play("ui_click", 0.6f);
|
||||
|
||||
public virtual float[] State
|
||||
{
|
||||
get => new[] { Hopper.Value, Dir.x, Dir.y, Dir.z };
|
||||
set
|
||||
{
|
||||
if (value == null || value.Length < 4) return;
|
||||
Hopper.Value = value[0];
|
||||
Seat(new Vector3(value[1], value[2], value[3]).normalized);
|
||||
}
|
||||
}
|
||||
|
||||
protected string MoodText
|
||||
{
|
||||
get
|
||||
{
|
||||
switch (Doing)
|
||||
{
|
||||
case RobotMood.Mowing: return Loc.T("mowing");
|
||||
case RobotMood.Unloading: return Loc.T("unloading");
|
||||
case RobotMood.Waiting: return Loc.T("waiting for room, connect a belt");
|
||||
case RobotMood.Finished: return Loc.T("everything in reach is mown");
|
||||
case RobotMood.NoCatcher: return Loc.T("hopper full, needs a catcher with room");
|
||||
default: return Loc.T("on the move");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
if (IsServer) Seat(Planet.Up(transform.position));
|
||||
_shown = _from = _to = At.Value;
|
||||
At.OnValueChanged += Heard;
|
||||
_engine = Sfx.Loop("robot_mower_loop", Body, 0f);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
At.OnValueChanged -= Heard;
|
||||
Release();
|
||||
if (_engine) Destroy(_engine.gameObject);
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
Release();
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
void Seat(Vector3 dir)
|
||||
{
|
||||
Dir = dir;
|
||||
At.Value = Planet.OnSurface(dir);
|
||||
}
|
||||
|
||||
/// <summary>The hammer put it somewhere else: everything it had planned is off.</summary>
|
||||
public virtual void Moved(Vector3 at)
|
||||
{
|
||||
_empty.Clear();
|
||||
_way.Clear();
|
||||
_next = 0;
|
||||
if (IsServer) Release();
|
||||
}
|
||||
|
||||
protected void Teleported(Vector3 at)
|
||||
{
|
||||
_shown = _from = _to = at;
|
||||
_leg = 1f;
|
||||
if (IsServer) Seat(Planet.Up(at));
|
||||
}
|
||||
|
||||
void Release()
|
||||
{
|
||||
if (_sector >= 0 && s_held.TryGetValue(_sector, out var who) && who == this) s_held.Remove(_sector);
|
||||
_sector = -1;
|
||||
}
|
||||
|
||||
/// <summary>The host cuts for real as it goes: the rest of the crew repeat the stroke they hear about.</summary>
|
||||
void Heard(Vector3 was, Vector3 now)
|
||||
{
|
||||
// a jump of more than a few ticks' walk is a teleport: no running there
|
||||
bool far = (now - _shown).sqrMagnitude > 400f;
|
||||
_from = far ? now : _shown;
|
||||
_to = now;
|
||||
_leg = far ? 1f : 0f;
|
||||
if (!IsServer && Mowing.Value && (now - was).sqrMagnitude < 400f) MowMap.Cut(was, now, Def.width, 0f, MowMap.PaintFeather);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!IsSpawned) return;
|
||||
if (IsServer)
|
||||
{
|
||||
_clock += Time.deltaTime;
|
||||
if (_clock >= Tick)
|
||||
{
|
||||
_clock -= Tick;
|
||||
float dt = Tick * Haste;
|
||||
// stopped from its settings: it waits where it is
|
||||
if ((_bp ? _bp : (_bp = GetComponent<BuildPiece>())) && _bp.Switched) { Mowing.Value = false; Mood.Value = (byte)RobotMood.Waiting; }
|
||||
else if (!Stay(dt)) Walk(dt);
|
||||
}
|
||||
}
|
||||
Show();
|
||||
if (_engine)
|
||||
{
|
||||
_engine.volume = Mathf.MoveTowards(_engine.volume, (Doing == RobotMood.Mowing ? EngineVolume : Doing == RobotMood.Travelling ? EngineVolume * 0.6f : 0f) * Sfx.SfxVolume, Time.deltaTime * 0.5f);
|
||||
_engine.pitch = Mathf.Lerp(1.5f, 1.1f, Def.width / 2f);
|
||||
}
|
||||
}
|
||||
|
||||
void Show()
|
||||
{
|
||||
var body = Body;
|
||||
if (!body) return;
|
||||
var aim = _to;
|
||||
var up = Planet.Up(aim);
|
||||
var flat = Vector3.ProjectOnPlane(aim - _from, up);
|
||||
_leg = Mathf.Min(1f, _leg + Time.deltaTime / Tick);
|
||||
_shown = Vector3.Lerp(_from, _to, _leg);
|
||||
// the nose, where the cutter is, goes first
|
||||
float nose = NoseOnBack ? -1f : 1f;
|
||||
if (flat.sqrMagnitude < 0.01f) flat = Vector3.ProjectOnPlane(body.forward * nose, up);
|
||||
if (flat.sqrMagnitude < 1e-4f) return;
|
||||
var was = body.rotation;
|
||||
var turn = Quaternion.Slerp(was, Quaternion.LookRotation(flat * nose, up), 1f - Mathf.Exp(-6f * Time.deltaTime));
|
||||
// it glides: no shake, no bob, the moving parts do the living
|
||||
bool going = _leg < 1f && (_to - _from).sqrMagnitude > 1e-4f;
|
||||
body.SetPositionAndRotation(_shown, turn);
|
||||
Animate(body, Vector3.SignedAngle(was * Vector3.forward, turn * Vector3.forward, up) / Mathf.Max(1e-3f, Time.deltaTime), going);
|
||||
}
|
||||
|
||||
// ───────────────────────── looks ─────────────────────────
|
||||
|
||||
// parts named for it by the model: Spin* turns while it mows, Blink* shuts now and then, Sway* springs about on its base
|
||||
readonly List<(Transform t, int axis)> _spin = new List<(Transform, int)>();
|
||||
readonly List<(Transform t, int axis, Vector3 size)> _blink = new List<(Transform, int, Vector3)>();
|
||||
readonly List<Transform> _sway = new List<Transform>();
|
||||
readonly List<(Transform t, int axis, float radius)> _wheels = new List<(Transform, int, float)>();
|
||||
Transform _fill;
|
||||
int _fillAxis = 1;
|
||||
float _roll, _level;
|
||||
bool _parts;
|
||||
float _spun, _nextBlink = 2f, _blinkAt = -1f, _swayX, _swayV, _wasGoing, _go;
|
||||
|
||||
void Animate(Transform body, float turnRate, bool going)
|
||||
{
|
||||
if (!_parts)
|
||||
{
|
||||
_parts = true;
|
||||
foreach (var c in body.GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
if (c.name.StartsWith("Spin")) _spin.Add((c, BaseRot.LocalAxisFor(c, body.up)));
|
||||
else if (c.name.StartsWith("Blink")) _blink.Add((c, BaseRot.LocalAxisFor(c, body.up), c.localScale));
|
||||
else if (c.name.StartsWith("Sway")) _sway.Add(c);
|
||||
else if (c.name.StartsWith("Wheel_"))
|
||||
{
|
||||
var r = c.GetComponent<Renderer>();
|
||||
_wheels.Add((c, BaseRot.LocalAxisFor(c, body.right), r ? Mathf.Max(0.05f, r.bounds.extents.y) : 0.2f));
|
||||
}
|
||||
else if (c.name == "Fill") { _fill = c; _fillAxis = BaseRot.LocalAxisFor(c, body.up); }
|
||||
if (c != body) BaseRot.Of(c);
|
||||
}
|
||||
}
|
||||
_spun += Time.deltaTime * (Mowing.Value ? 1400f : 0f);
|
||||
foreach (var (t, axis) in _spin)
|
||||
t.localRotation = BaseRot.Of(t) * Quaternion.AngleAxis(_spun, axis == 0 ? Vector3.right : axis == 1 ? Vector3.up : Vector3.forward);
|
||||
// the wheels roll with the ground going by, the clippings rise in the hopper
|
||||
// eased, so the frame between two steps doesn't read as a stop and a start
|
||||
_go = Mathf.MoveTowards(_go, going ? 1f : 0f, Time.deltaTime * 2.5f);
|
||||
float speed = (_to - _from).magnitude / Tick * _go;
|
||||
_roll += speed * Time.deltaTime * Mathf.Rad2Deg;
|
||||
foreach (var (t, axis, radius) in _wheels)
|
||||
t.localRotation = BaseRot.Of(t) * Quaternion.AngleAxis(_roll / radius, axis == 0 ? Vector3.right : axis == 1 ? Vector3.up : Vector3.forward);
|
||||
if (_fill)
|
||||
{
|
||||
_level = Mathf.Lerp(_level, Mathf.Clamp01(Hopper.Value / Mathf.Max(1f, HopperCap)), Time.deltaTime * 3f);
|
||||
var f = _fill.localScale;
|
||||
f[_fillAxis] = Mathf.Max(0.001f, _level);
|
||||
_fill.localScale = f;
|
||||
}
|
||||
// blink: shut over a tenth of a second, open again, every two to six seconds
|
||||
if (Time.time > _nextBlink) { _blinkAt = Time.time; _nextBlink = Time.time + Random.Range(2f, 6f); }
|
||||
float b = _blinkAt < 0f ? 1f : Mathf.Clamp01(Mathf.Abs(Time.time - _blinkAt - 0.08f) / 0.08f);
|
||||
foreach (var (t, axis, size) in _blink)
|
||||
{
|
||||
var s = size;
|
||||
s[axis] *= Mathf.Max(0.05f, b);
|
||||
t.localScale = s;
|
||||
}
|
||||
// the antenna whips back when it sets off or stops, and leans out of the turns
|
||||
float kick = _go - _wasGoing;
|
||||
_wasGoing = _go;
|
||||
_swayV += (-90f * _swayX - 5f * _swayV) * Time.deltaTime - kick * 2.5f + Mathf.Clamp(turnRate, -200f, 200f) * 0.0004f;
|
||||
_swayX += _swayV * Time.deltaTime;
|
||||
foreach (var t in _sway)
|
||||
t.localRotation = Quaternion.AngleAxis(_swayX * 40f, t.parent.InverseTransformDirection(body.right)) * BaseRot.Of(t);
|
||||
}
|
||||
|
||||
// ───────────────────────── walking ─────────────────────────
|
||||
|
||||
void Walk(float dt)
|
||||
{
|
||||
if (!Homing && _next >= _way.Count)
|
||||
{
|
||||
if (Time.time < _idleUntil) return;
|
||||
if (!FindWork())
|
||||
{
|
||||
_idleUntil = Time.time + IdleWait;
|
||||
NoWork();
|
||||
if (!Homing) return;
|
||||
}
|
||||
}
|
||||
var goal = Homing ? HomeDir : _way[_next];
|
||||
var from = Planet.OnSurface(Dir);
|
||||
// not RotateTowards: it calls anything under a tenth of a degree "there already", and that is 4 m on this ball
|
||||
var gap = goal - Dir;
|
||||
float step = Def.speed * Boost * dt / Planet.Radius;
|
||||
if (gap.magnitude > step) Dir = (Dir + gap.normalized * step).normalized;
|
||||
else
|
||||
{
|
||||
Dir = goal;
|
||||
if (Homing)
|
||||
{
|
||||
Homing = false;
|
||||
Arrived();
|
||||
}
|
||||
else
|
||||
{
|
||||
_next++;
|
||||
_travel = false;
|
||||
}
|
||||
}
|
||||
var to = Planet.OnSurface(Dir);
|
||||
if (Mowing.Value) Hopper.Value += MowMap.Cut(from, to, Def.width, 0f, MowMap.PaintFeather) * GameDefs.GrassDensity;
|
||||
Mowing.Value = !Homing && !_travel && _next < _way.Count;
|
||||
Mood.Value = (byte)(Mowing.Value ? RobotMood.Mowing : RobotMood.Travelling);
|
||||
At.Value = to;
|
||||
}
|
||||
|
||||
/// <summary>Off to unload, then back to the very spot it left.</summary>
|
||||
protected void GoHome()
|
||||
{
|
||||
if (_next < _way.Count) _way.Insert(_next, Dir);
|
||||
_travel = true;
|
||||
Homing = true;
|
||||
}
|
||||
|
||||
// ───────────────────────── planning ─────────────────────────
|
||||
|
||||
/// <summary>Sectors around where it started, rings out to its reach.</summary>
|
||||
public int Area()
|
||||
{
|
||||
Spread(HexGrid.SectorAt(Planet.Up(Origin)), id => false);
|
||||
return s_seen.Count;
|
||||
}
|
||||
|
||||
bool FindWork()
|
||||
{
|
||||
Release();
|
||||
return Spread(HexGrid.SectorAt(Planet.Up(Origin)), TryPlan);
|
||||
}
|
||||
|
||||
bool TryPlan(int id)
|
||||
{
|
||||
if (_empty.Contains(id) || MowMap.Cleared(id) >= 1f) return false;
|
||||
if (s_held.TryGetValue(id, out var who) && who) return false;
|
||||
Plan(id);
|
||||
if (_way.Count == 0)
|
||||
{
|
||||
_empty.Add(id);
|
||||
return false;
|
||||
}
|
||||
_sector = id;
|
||||
s_held[id] = this;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Spread(int start, System.Func<int, bool> take)
|
||||
{
|
||||
s_seen.Clear();
|
||||
s_queue.Clear();
|
||||
s_seen.Add(start);
|
||||
s_queue.Enqueue((start, 0));
|
||||
while (s_queue.Count > 0 && s_seen.Count < SearchLimit)
|
||||
{
|
||||
var (id, ring) = s_queue.Dequeue();
|
||||
if (take(id)) return true;
|
||||
if (ring >= Reach) continue;
|
||||
foreach (int n in HexGrid.Get(id).neighbours)
|
||||
if (s_seen.Add(n)) s_queue.Enqueue((n, ring + 1));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Rows across the sector, edge to edge, and only where there is something to cut.</summary>
|
||||
void Plan(int id)
|
||||
{
|
||||
_way.Clear();
|
||||
_next = 0;
|
||||
_travel = true;
|
||||
var s = HexGrid.Get(id);
|
||||
MowMap.Rows(id, Def.width, s_rows);
|
||||
bool flip = false;
|
||||
foreach (var r in s_rows)
|
||||
{
|
||||
var a = Flat(s, r.y - Overrun, r.x);
|
||||
var b = Flat(s, r.z + Overrun, r.x);
|
||||
_way.Add(flip ? b : a);
|
||||
_way.Add(flip ? a : b);
|
||||
flip = !flip;
|
||||
}
|
||||
if (_way.Count > 1 && Vector3.Dot(_way[_way.Count - 1], Dir) > Vector3.Dot(_way[0], Dir)) _way.Reverse();
|
||||
}
|
||||
|
||||
static Vector3 Flat(HexGrid.Sector s, float u, float v) => (s.c * Planet.Radius + s.e1 * u + s.e2 * v).normalized;
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Mowbot.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Mowbot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9b918cdea2cadd346b46a3bad08a1963
|
||||
91
Assets/Scripts/Gameplay/PowerBattery.cs
Normal file
91
Assets/Scripts/Gameplay/PowerBattery.cs
Normal file
@ -0,0 +1,91 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A battery takes what the panels have to spare and gives it back when they fall short, so machines keep running through
|
||||
/// the night at whatever the battery can deliver. It charges and empties over time, at no more than its rated power.
|
||||
/// </summary>
|
||||
public class PowerBattery : PowerNode, IPieceState
|
||||
{
|
||||
public Transform gauge;
|
||||
public Renderer lamp;
|
||||
|
||||
public readonly NetworkVariable<float> Stored = new NetworkVariable<float>();
|
||||
/// <summary>Kilowatts going in, or out if below zero.</summary>
|
||||
public readonly NetworkVariable<float> Flow = new NetworkVariable<float>();
|
||||
|
||||
MaterialPropertyBlock _mpb;
|
||||
Vector3 _gaugeScale = Vector3.one;
|
||||
AudioSource _hum;
|
||||
bool _wasFull;
|
||||
static readonly int Emission = Shader.PropertyToID("_EmissionColor");
|
||||
|
||||
BatteryDef Def => GameDefs.Battery(Piece.piece);
|
||||
public override float Radius => Def.radius;
|
||||
public float Capacity => Def.kwh;
|
||||
public float Rate => Def.kw;
|
||||
/// <summary>How many times its output rating a battery may charge at.</summary>
|
||||
public const float ChargeBoost = 6f;
|
||||
public bool Full => Stored.Value >= Capacity - 0.001f;
|
||||
|
||||
public float[] State
|
||||
{
|
||||
get => new[] { Stored.Value };
|
||||
set { if (value != null && value.Length > 0) Stored.Value = Mathf.Min(value[0], Capacity); }
|
||||
}
|
||||
|
||||
public override string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
string doing = Flow.Value > 0.01f ? Loc.F("charging at {0:0.#} kW", Flow.Value) : Flow.Value < -0.01f ? Loc.F("giving {0:0.#} kW, {1:0} min left at this rate", -Flow.Value, Stored.Value / -Flow.Value * 60f) : Full ? Loc.T("full") : Loc.T("resting");
|
||||
return Loc.F("{0}: {1:0.0} of {2:0} kWh, {3}. {4}", Piece.Def.name, Stored.Value, Capacity, doing, Network);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Server: moves kilowatts for dt seconds, in or out if below zero. Returns what really moved. Kilowatt-hours are real hours.</summary>
|
||||
public float Charge(float kw, float dt)
|
||||
{
|
||||
float can = kw >= 0f ? (Capacity - Stored.Value) * 3600f / dt : Stored.Value * 3600f / dt;
|
||||
// they take charge much faster than they give it: a rack fills from spare sun in a few minutes, not half an hour
|
||||
float done = Mathf.Sign(kw) * Mathf.Min(Mathf.Abs(kw), kw >= 0f ? Rate * ChargeBoost : Rate, can);
|
||||
if (done != 0f) Stored.Value = Mathf.Clamp(Stored.Value + done * dt / 3600f, 0f, Capacity);
|
||||
Write(Flow, done);
|
||||
return done;
|
||||
}
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
if (gauge) _gaugeScale = gauge.localScale;
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
base.OnNetworkSpawn();
|
||||
_hum = Sfx.Loop("battery_hum_loop", transform, 0f);
|
||||
_wasFull = Full;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
float full = Capacity > 0f ? Stored.Value / Capacity : 0f;
|
||||
if (_hum) _hum.volume = Mathf.MoveTowards(_hum.volume, Mathf.Abs(Flow.Value) > 0.01f ? 0.3f * Sfx.SfxVolume : 0f, Time.deltaTime * 0.6f);
|
||||
if (Full && !_wasFull) Sfx.PlayAt("battery_full", transform.position + transform.up, 0.5f);
|
||||
_wasFull = Full;
|
||||
if (gauge)
|
||||
{
|
||||
var s = _gaugeScale;
|
||||
s.y *= Mathf.Max(0.02f, full);
|
||||
gauge.localScale = s;
|
||||
}
|
||||
if (!lamp) return;
|
||||
var c = Flow.Value > 0.01f ? new Color(0.2f, 1f, 0.35f) : Flow.Value < -0.01f ? new Color(1f, 0.7f, 0.15f) : full > 0.02f ? new Color(0.2f, 0.5f, 1f) : new Color(1f, 0.15f, 0.1f);
|
||||
lamp.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(Emission, c * 2.2f);
|
||||
lamp.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerBattery.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerBattery.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0f7a32d3f065345488fb8707d4d4c99a
|
||||
112
Assets/Scripts/Gameplay/PowerGrid.cs
Normal file
112
Assets/Scripts/Gameplay/PowerGrid.cs
Normal file
@ -0,0 +1,112 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Server: who powers whom. Nodes and machines that reach each other make one network. The sun goes to the machines first,
|
||||
/// batteries make up what's missing, and whatever is left over charges them. A machine gets the share of its power that the
|
||||
/// network can give, and that share is how fast it runs.
|
||||
/// </summary>
|
||||
public static class PowerGrid
|
||||
{
|
||||
class Net
|
||||
{
|
||||
public readonly List<PowerNode> nodes = new List<PowerNode>();
|
||||
public readonly List<Machine> machines = new List<Machine>();
|
||||
public readonly List<PowerBattery> batteries = new List<PowerBattery>();
|
||||
}
|
||||
|
||||
static readonly List<Net> s_nets = new List<Net>();
|
||||
static readonly HashSet<Machine> s_seenM = new HashSet<Machine>();
|
||||
static readonly HashSet<PowerNode> s_seenN = new HashSet<PowerNode>();
|
||||
static int s_version = -1, s_nodes, s_machines;
|
||||
|
||||
public static bool Reaches(PowerNode n, Vector3 at) => (n.transform.position - at).sqrMagnitude <= n.Radius * n.Radius;
|
||||
|
||||
public static bool Joined(PowerNode a, PowerNode b)
|
||||
{
|
||||
float r = Mathf.Max(a.Radius, b.Radius);
|
||||
return (a.transform.position - b.transform.position).sqrMagnitude <= r * r;
|
||||
}
|
||||
|
||||
/// <summary>Is there power reaching this spot?</summary>
|
||||
public static bool Covers(Vector3 at)
|
||||
{
|
||||
foreach (var n in PowerNode.All) if (n && Reaches(n, at)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void Tick(float dt)
|
||||
{
|
||||
if (s_version != BuildPiece.Version || s_nodes != PowerNode.All.Count || s_machines != Machine.All.Count) Rebuild();
|
||||
foreach (var net in s_nets) Balance(net, dt);
|
||||
}
|
||||
|
||||
static void Rebuild()
|
||||
{
|
||||
s_version = BuildPiece.Version;
|
||||
s_nodes = PowerNode.All.Count;
|
||||
s_machines = Machine.All.Count;
|
||||
s_nets.Clear();
|
||||
s_seenM.Clear();
|
||||
s_seenN.Clear();
|
||||
foreach (var m in Machine.All)
|
||||
{
|
||||
if (!m || s_seenM.Contains(m)) continue;
|
||||
var net = new Net();
|
||||
Walk(m, net);
|
||||
s_nets.Add(net);
|
||||
}
|
||||
foreach (var n in PowerNode.All)
|
||||
{
|
||||
if (!n || s_seenN.Contains(n)) continue;
|
||||
var net = new Net();
|
||||
Walk(n, net);
|
||||
s_nets.Add(net);
|
||||
}
|
||||
}
|
||||
|
||||
static void Walk(Machine m, Net net)
|
||||
{
|
||||
s_seenM.Add(m);
|
||||
net.machines.Add(m);
|
||||
foreach (var n in PowerNode.All)
|
||||
if (n && !s_seenN.Contains(n) && Reaches(n, m.transform.position)) Walk(n, net);
|
||||
}
|
||||
|
||||
static void Walk(PowerNode n, Net net)
|
||||
{
|
||||
s_seenN.Add(n);
|
||||
net.nodes.Add(n);
|
||||
if (n is PowerBattery b) net.batteries.Add(b);
|
||||
foreach (var other in PowerNode.All)
|
||||
if (other && !s_seenN.Contains(other) && Joined(n, other)) Walk(other, net);
|
||||
foreach (var m in Machine.All)
|
||||
if (m && !s_seenM.Contains(m) && Reaches(n, m.transform.position)) Walk(m, net);
|
||||
}
|
||||
|
||||
static void Balance(Net net, float dt)
|
||||
{
|
||||
float sun = 0f, asked = 0f, held = 0f, cap = 0f;
|
||||
foreach (var n in net.nodes) if (n) sun += n.Sunlight;
|
||||
foreach (var m in net.machines) if (m && m.Busy) asked += m.Kw;
|
||||
|
||||
// short of sun the batteries top it up, with sun to spare they fill, shared out evenly among them
|
||||
float want = asked - sun, given = 0f;
|
||||
for (int i = 0; i < net.batteries.Count; i++)
|
||||
{
|
||||
var b = net.batteries[i];
|
||||
if (!b) continue;
|
||||
float out_ = b.Charge(-(want - given) / (net.batteries.Count - i), dt);
|
||||
given -= out_;
|
||||
held += b.Stored.Value;
|
||||
cap += b.Capacity;
|
||||
}
|
||||
float supply = sun + Mathf.Max(0f, given);
|
||||
float pace = net.nodes.Count == 0 ? 0f : asked > 0f ? Mathf.Clamp01(supply / asked) : supply > 0f || held > 0f ? 1f : 0f;
|
||||
foreach (var m in net.machines) if (m && !Mathf.Approximately(m.Power.Value, pace)) m.Power.Value = pace;
|
||||
foreach (var n in net.nodes) if (n) n.Report(supply, asked, held, cap);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerGrid.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerGrid.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: db2db15fad6db7c4ab2510b6d7efb8c6
|
||||
69
Assets/Scripts/Gameplay/PowerNode.cs
Normal file
69
Assets/Scripts/Gameplay/PowerNode.cs
Normal file
@ -0,0 +1,69 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A piece of the power network: a panel, a battery or a pole. Nodes join up with whatever lies inside the longer of
|
||||
/// their radii, machines with any node that reaches them, and everything joined shares one supply.
|
||||
/// </summary>
|
||||
public abstract class PowerNode : NetworkBehaviour, IInteractable
|
||||
{
|
||||
public static readonly List<PowerNode> All = new List<PowerNode>();
|
||||
|
||||
/// <summary>What the whole network this node is on is doing, in kilowatts and kilowatt-hours.</summary>
|
||||
public readonly NetworkVariable<float> Supply = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Asked = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Held = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Cap = new NetworkVariable<float>();
|
||||
|
||||
BuildPiece _piece;
|
||||
|
||||
protected BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
public abstract float Radius { get; }
|
||||
/// <summary>Where a wire ties on.</summary>
|
||||
public virtual float WireHeight => 1.6f;
|
||||
/// <summary>Kilowatts the sun gives it right now.</summary>
|
||||
public virtual float Sunlight => 0f;
|
||||
|
||||
public abstract string Prompt { get; }
|
||||
public bool CanInteract => false;
|
||||
public void Interact() { }
|
||||
|
||||
/// <summary>The network in a few words, for the prompt.</summary>
|
||||
protected string Network
|
||||
{
|
||||
get
|
||||
{
|
||||
bool batteries = Cap.Value > 0f;
|
||||
if (Asked.Value <= 0f)
|
||||
return batteries ? Loc.F("nothing to run, {0:0.#} kW free, batteries {1:0.0} of {2:0} kWh", Supply.Value, Held.Value, Cap.Value) : Loc.F("nothing to run, {0:0.#} kW free", Supply.Value);
|
||||
float at = Mathf.Clamp01(Supply.Value / Asked.Value) * 100f;
|
||||
return batteries ? Loc.F("machines at {0:0}%, {1:0.#} of {2:0.#} kW, batteries {3:0.0} of {4:0} kWh", at, Supply.Value, Asked.Value, Held.Value, Cap.Value) : Loc.F("machines at {0:0}%, {1:0.#} of {2:0.#} kW", at, Supply.Value, Asked.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn() => All.Add(this);
|
||||
public override void OnNetworkDespawn() => All.Remove(this);
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public void Report(float supply, float asked, float held, float cap)
|
||||
{
|
||||
Write(Supply, supply);
|
||||
Write(Asked, asked);
|
||||
Write(Held, held);
|
||||
Write(Cap, cap);
|
||||
}
|
||||
|
||||
protected static void Write(NetworkVariable<float> v, float value)
|
||||
{
|
||||
if (Mathf.Abs(v.Value - value) > 0.01f || (value == 0f && v.Value != 0f)) v.Value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerNode.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerNode.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 513b7b26d9018284488e552fbcfcee44
|
||||
10
Assets/Scripts/Gameplay/PowerPole.cs
Normal file
10
Assets/Scripts/Gameplay/PowerPole.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A pole carries the network further: it makes nothing and stores nothing, but it reaches a long way and shows its wires.</summary>
|
||||
public class PowerPole : PowerNode
|
||||
{
|
||||
public override float Radius => GameDefs.PoleReach;
|
||||
public override float WireHeight => GameDefs.PoleHeight;
|
||||
public override string Prompt => Loc.F("{0}: reaches {1:0} m, {2}", Piece.Def.name, Radius, Network);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerPole.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerPole.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ae848234fa7ef4648b31d0d8897b67ae
|
||||
101
Assets/Scripts/Gameplay/Reaper.cs
Normal file
101
Assets/Scripts/Gameplay/Reaper.cs
Normal file
@ -0,0 +1,101 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>The Reaper belongs to no dock: it goes from sector to sector over the whole planet and shoots its bundles into a catcher, however far.</summary>
|
||||
public class Reaper : Mowbot
|
||||
{
|
||||
const float ShotEvery = 0.5f, ShowEvery = 0.4f, ReelSpeed = 420f;
|
||||
|
||||
public Transform muzzle, reel;
|
||||
|
||||
float _nextShow, _spun;
|
||||
int _reelAxis = -1;
|
||||
|
||||
protected override Transform Body => transform;
|
||||
protected override Vector3 Origin => At.Value;
|
||||
protected override int Reach => 100000;
|
||||
|
||||
public override string Prompt => Loc.F("{0}: {1}, {2} of {3}", Def.name, MoodText, GameDefs.Kilos(Hopper.Value), GameDefs.Kilos(HopperCap));
|
||||
|
||||
public override void Moved(Vector3 at)
|
||||
{
|
||||
base.Moved(at);
|
||||
Teleported(at);
|
||||
}
|
||||
|
||||
protected override bool Stay(float dt)
|
||||
{
|
||||
int shots = Mathf.CeilToInt(dt / ShotEvery);
|
||||
while (Hopper.Value >= GameDefs.BundleKg && shots-- > 0)
|
||||
{
|
||||
var c = Catcher.WithRoom();
|
||||
if (!c) break;
|
||||
c.ServerCatch(GameDefs.BundleKg);
|
||||
Hopper.Value -= GameDefs.BundleKg;
|
||||
if (Time.time >= _nextShow)
|
||||
{
|
||||
_nextShow = Time.time + ShowEvery;
|
||||
ShotRpc(c.transform.position + c.transform.up * 2f);
|
||||
}
|
||||
}
|
||||
if (Hopper.Value < HopperCap) return false;
|
||||
Mowing.Value = false;
|
||||
Mood.Value = (byte)RobotMood.NoCatcher;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override void NoWork() => Mood.Value = (byte)RobotMood.Finished;
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void ShotRpc(Vector3 to)
|
||||
{
|
||||
BundleShot.Fly(muzzle ? muzzle.position : At.Value + transform.up * 1.5f, to);
|
||||
Sfx.PlayAt("launcher_fire", At.Value, 0.5f, 1.2f);
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (!reel || !Mowing.Value) return;
|
||||
if (_reelAxis < 0) _reelAxis = BaseRot.LocalAxisFor(reel, transform.right);
|
||||
_spun += ReelSpeed * Time.deltaTime;
|
||||
var axis = _reelAxis == 0 ? Vector3.right : _reelAxis == 1 ? Vector3.up : Vector3.forward;
|
||||
reel.localRotation = BaseRot.Of(reel) * Quaternion.Euler(axis * _spun);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A bundle in the air. Only for the eyes: the catcher has it already.</summary>
|
||||
public class BundleShot : MonoBehaviour
|
||||
{
|
||||
const float Near = 600f;
|
||||
|
||||
Vector3 _from, _to;
|
||||
float _t, _time, _arc;
|
||||
|
||||
public static void Fly(Vector3 from, Vector3 to)
|
||||
{
|
||||
var cam = Camera.main;
|
||||
if (!cam || (Vector3.Distance(cam.transform.position, from) > Near && Vector3.Distance(cam.transform.position, to) > Near)) return;
|
||||
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
Destroy(go.GetComponent<Collider>());
|
||||
go.transform.localScale = Vector3.one * 0.5f;
|
||||
go.GetComponent<Renderer>().sharedMaterial = BuildLook.Mat("M_Bundle", new Color(0.62f, 0.78f, 0.28f));
|
||||
var shot = go.AddComponent<BundleShot>();
|
||||
float far = Vector3.Distance(from, to);
|
||||
shot._from = Planet.Up(from);
|
||||
shot._to = Planet.Up(to);
|
||||
shot._time = Mathf.Clamp(1f + far / 150f, 1f, 8f);
|
||||
shot._arc = Mathf.Min(8f + far * 0.25f, 200f);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
_t += Time.deltaTime / _time;
|
||||
if (_t >= 1f) { Destroy(gameObject); return; }
|
||||
var d = Vector3.Slerp(_from, _to, _t);
|
||||
transform.position = Planet.OnSurface(d) + d * (1.5f + Mathf.Sin(_t * Mathf.PI) * _arc);
|
||||
transform.Rotate(180f * Time.deltaTime, 90f * Time.deltaTime, 0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Reaper.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Reaper.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b2c8b41ca64137f41ade2157da18f05a
|
||||
79
Assets/Scripts/Gameplay/RobotDock.cs
Normal file
79
Assets/Scripts/Gameplay/RobotDock.cs
Normal file
@ -0,0 +1,79 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A robot mower and its dock: it works the rings of sectors around the dock, and the dock ties what it brings into bundles for the belt.</summary>
|
||||
public class RobotDock : Mowbot, IPorts
|
||||
{
|
||||
const float SiloRoom = 100f, UnloadRate = 5f;
|
||||
|
||||
public Transform bot;
|
||||
public readonly NetworkVariable<float> Silo = new NetworkVariable<float>();
|
||||
|
||||
bool _unloading;
|
||||
int _turn, _area;
|
||||
|
||||
protected override Transform Body => bot;
|
||||
protected override bool NoseOnBack => true;
|
||||
protected override Vector3 Origin => transform.position;
|
||||
protected override int Reach => Def.reach;
|
||||
protected override Vector3 HomeDir => Planet.Up(transform.position);
|
||||
|
||||
public override string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_area == 0) _area = Area();
|
||||
return Loc.F("{0}: {1}, {2} of {3}, {4} sectors, dock holds {5}", Def.name, MoodText, GameDefs.Kilos(Hopper.Value), GameDefs.Kilos(HopperCap), _area, GameDefs.Kilos(Silo.Value));
|
||||
}
|
||||
}
|
||||
|
||||
public override float[] State
|
||||
{
|
||||
get => new[] { Hopper.Value, Dir.x, Dir.y, Dir.z, Silo.Value };
|
||||
set
|
||||
{
|
||||
base.State = value;
|
||||
if (value != null && value.Length > 4) Silo.Value = value[4];
|
||||
}
|
||||
}
|
||||
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
|
||||
protected override bool Stay(float dt)
|
||||
{
|
||||
BeltNet.Drain(GetComponent<BuildPiece>(), Silo, ref _turn);
|
||||
if (_unloading)
|
||||
{
|
||||
float give = Mathf.Min(Hopper.Value, UnloadRate * dt, SiloRoom - Silo.Value);
|
||||
if (give > 0f)
|
||||
{
|
||||
Hopper.Value -= give;
|
||||
Silo.Value += give;
|
||||
}
|
||||
if (Hopper.Value >= 0.01f)
|
||||
{
|
||||
Mood.Value = (byte)(give > 0f ? RobotMood.Unloading : RobotMood.Waiting);
|
||||
return true;
|
||||
}
|
||||
Hopper.Value = 0f;
|
||||
_unloading = false;
|
||||
}
|
||||
if (!Homing && Hopper.Value >= HopperCap) GoHome();
|
||||
return false;
|
||||
}
|
||||
|
||||
protected override void Arrived() => _unloading = true;
|
||||
|
||||
protected override void NoWork()
|
||||
{
|
||||
if (Vector3.Dot(Dir, HomeDir) < 0.9999999f || Hopper.Value > 0f) GoHome();
|
||||
else Mood.Value = (byte)RobotMood.Finished;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/RobotDock.cs.meta
Normal file
2
Assets/Scripts/Gameplay/RobotDock.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7bf64db802ef6514b9f51564dfd066a2
|
||||
18
Assets/Scripts/Gameplay/ShopTerminal.cs
Normal file
18
Assets/Scripts/Gameplay/ShopTerminal.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>The upgrade console. Opens the crew's upgrade matrix for the local player.</summary>
|
||||
public class ShopTerminal : MonoBehaviour, IInteractable
|
||||
{
|
||||
public Renderer screen;
|
||||
public string Prompt => Loc.T("GreenHaul console — upgrade matrix");
|
||||
public bool CanInteract => TeamState.Instance;
|
||||
public void Interact()
|
||||
{
|
||||
Sfx.Play("ui_open");
|
||||
UIRoot.I?.OpenShop();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/ShopTerminal.cs.meta
Normal file
2
Assets/Scripts/Gameplay/ShopTerminal.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0b5f23ce6e6c56a458b8549e8b5d56d1
|
||||
68
Assets/Scripts/Gameplay/SiloPiece.cs
Normal file
68
Assets/Scripts/Gameplay/SiloPiece.cs
Normal file
@ -0,0 +1,68 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A building that holds loose grass and sends it out of its ports as bundles, one every fifth of a second.</summary>
|
||||
public abstract class SiloPiece : NetworkBehaviour, IInteractable, IPorts, IPieceState
|
||||
{
|
||||
const float Every = 0.2f;
|
||||
|
||||
/// <summary>Everything a mower can unload onto: garages and unload bays.</summary>
|
||||
public static readonly List<SiloPiece> Pads = new List<SiloPiece>();
|
||||
|
||||
/// <summary>Is this spot on the part a mower drives onto to unload?</summary>
|
||||
public virtual bool OnPad(Vector3 p) => false;
|
||||
/// <summary>The middle of that part, for markers.</summary>
|
||||
public virtual Vector3 PadSpot => transform.position;
|
||||
public virtual string PadName => Loc.T("Unload");
|
||||
|
||||
public static SiloPiece PadUnder(Vector3 p)
|
||||
{
|
||||
foreach (var s in Pads) if (s && s.IsSpawned && s.OnPad(p)) return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn() { if (!Pads.Contains(this)) Pads.Add(this); }
|
||||
public override void OnNetworkDespawn() => Pads.Remove(this);
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
Pads.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public readonly NetworkVariable<float> Silo = new NetworkVariable<float>();
|
||||
|
||||
float _nextOut;
|
||||
int _turn;
|
||||
|
||||
public abstract string Prompt { get; }
|
||||
public virtual bool CanInteract => TeamState.Instance;
|
||||
public abstract void Interact();
|
||||
public abstract void Ports(List<Port> into);
|
||||
|
||||
public float[] State
|
||||
{
|
||||
get => new[] { Silo.Value };
|
||||
set { if (value != null && value.Length > 0) Silo.Value = value[0]; }
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void TakeRpc(float kg)
|
||||
{
|
||||
if (kg > 0f) Silo.Value += kg;
|
||||
}
|
||||
|
||||
protected virtual void Update()
|
||||
{
|
||||
if (!IsServer || !IsSpawned || Time.time < _nextOut) return;
|
||||
var piece = GetComponent<BuildPiece>();
|
||||
_nextOut = Time.time + Every / (piece ? piece.TierMul : 1f);
|
||||
// hatches shut: it only fills up
|
||||
if (piece && piece.Switched) return;
|
||||
BeltNet.Drain(GetComponent<BuildPiece>(), Silo, ref _turn);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/SiloPiece.cs.meta
Normal file
2
Assets/Scripts/Gameplay/SiloPiece.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aace0ae7268a794419fc72ce6c28a608
|
||||
66
Assets/Scripts/Gameplay/SolarPanel.cs
Normal file
66
Assets/Scripts/Gameplay/SolarPanel.cs
Normal file
@ -0,0 +1,66 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A solar panel feeds its network with what the sun gives it: a fixed panel less when the sun is low, a tracker its full
|
||||
/// power all day, nothing at night. Keeping power for the dark takes a battery.
|
||||
/// </summary>
|
||||
public class SolarPanel : PowerNode
|
||||
{
|
||||
public readonly NetworkVariable<float> Output = new NetworkVariable<float>();
|
||||
|
||||
Transform _head;
|
||||
Quaternion _rest;
|
||||
|
||||
PanelDef Def => GameDefs.Panel(Piece.piece);
|
||||
public override float Radius => Def.radius;
|
||||
|
||||
public override float Sunlight
|
||||
{
|
||||
get
|
||||
{
|
||||
float h = Sun.Height(Planet.Up(transform.position));
|
||||
float kw = Def.kw * (Def.tracker ? Mathf.Clamp01(h * 8f) : Mathf.Clamp01(h * 1.4f)) * (TeamState.Instance ? WeatherFx.SolarOf(TeamState.Instance.WeatherNow) : 1f);
|
||||
if (IsServer) Write(Output, kw);
|
||||
return kw;
|
||||
}
|
||||
}
|
||||
|
||||
public override string Prompt => Loc.F("{0}: {1:0.#} of {2:0.#} kW, reaches {3:0} m. {4}", Piece.Def.name, Output.Value, Def.kw, Def.radius, Network);
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_head = Build(transform, GetComponent<BuildPiece>().piece);
|
||||
_rest = Quaternion.Inverse(transform.rotation) * _head.rotation;
|
||||
var box = gameObject.AddComponent<BoxCollider>();
|
||||
box.center = Vector3.up * 1.5f;
|
||||
box.size = new Vector3(1.2f, 3f, 1.2f);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
// the tracker's panel follows the sun, on every peer
|
||||
if (!Def.tracker || !_head) return;
|
||||
var up = Planet.Up(transform.position);
|
||||
var aim = Sun.Height(up) > 0f ? Sun.Dir : up;
|
||||
_head.rotation = Quaternion.RotateTowards(_head.rotation, Quaternion.FromToRotation(Vector3.up, aim) * _rest, 12f * Time.deltaTime);
|
||||
}
|
||||
|
||||
/// <summary>The model, shared with the ghost. Returns the part that carries the cells.</summary>
|
||||
public static Transform Build(Transform root, PieceId id)
|
||||
{
|
||||
var inst = Instantiate(AssetBank.I.Model(id == PieceId.SolarS ? "SM_SolarPost" : id == PieceId.SolarM ? "SM_SolarPair" : "SM_SolarTracker"), root);
|
||||
inst.transform.localPosition = Vector3.zero;
|
||||
Transform head = inst.transform;
|
||||
foreach (var t in inst.GetComponentsInChildren<Transform>())
|
||||
{
|
||||
t.gameObject.layer = root.gameObject.layer;
|
||||
if (t.name == "Head") head = t;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/SolarPanel.cs.meta
Normal file
2
Assets/Scripts/Gameplay/SolarPanel.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 97280bc68ee618d4c8898c731fe0f110
|
||||
85
Assets/Scripts/Gameplay/Spawner.cs
Normal file
85
Assets/Scripts/Gameplay/Spawner.cs
Normal file
@ -0,0 +1,85 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Server-side spawning of everything dynamic: crew state, the starter kit, cargo, builds and machines.</summary>
|
||||
public class Spawner : MonoBehaviour
|
||||
{
|
||||
public static Spawner Instance { get; private set; }
|
||||
|
||||
public NetworkObject teamStatePrefab;
|
||||
public NetworkObject[] cargoPrefabs = new NetworkObject[3]; // by CargoKind
|
||||
public NetworkObject[] vehiclePrefabs = new NetworkObject[(int)VehicleKind.Count];
|
||||
public NetworkObject[] piecePrefabs; // by PieceId
|
||||
public Transform dock; // DockZone: vehicles spawn along it
|
||||
|
||||
NetworkManager Nm => NetworkManager.Singleton;
|
||||
TeamState Ts => TeamState.Instance;
|
||||
|
||||
void Awake() { Instance = this; }
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (NetSession.Instance) NetSession.Instance.Started += OnSessionStarted;
|
||||
}
|
||||
|
||||
void OnSessionStarted()
|
||||
{
|
||||
if (!Nm.IsServer) return;
|
||||
var ts = Instantiate(teamStatePrefab);
|
||||
ts.Spawn(true);
|
||||
}
|
||||
|
||||
// ───────────────────────── starter kit ─────────────────────────
|
||||
|
||||
/// <summary>A fresh base: the grass depot is all you get. Company property, can't be removed.</summary>
|
||||
public void ServerSpawnStarter()
|
||||
{
|
||||
var ts = Ts;
|
||||
if (ts) ts.ServerSpawnPiece(PieceId.Depot, new Vector3(-2f, 0f, -1f), Quaternion.identity, Vector3.zero, -1, true);
|
||||
}
|
||||
|
||||
// ───────────────────────── cargo ─────────────────────────
|
||||
|
||||
public Cargo SpawnCargo(CargoKind kind, Vector3 pos, Quaternion rot, Vector3 velocity, float kg = GameDefs.BundleKg)
|
||||
{
|
||||
var prefab = cargoPrefabs[(int)kind];
|
||||
if (!prefab || !Nm.IsServer) return null;
|
||||
var no = Instantiate(prefab, pos, rot);
|
||||
var c = no.GetComponent<Cargo>();
|
||||
c.Kg.Value = kg;
|
||||
no.Spawn(true);
|
||||
var rb = no.GetComponent<Rigidbody>();
|
||||
if (rb && !rb.isKinematic) rb.linearVelocity = velocity;
|
||||
return c;
|
||||
}
|
||||
|
||||
// ───────────────────────── builds ─────────────────────────
|
||||
|
||||
public BuildPiece SpawnPiece(PieceId id, Vector3 pos, Quaternion rot, Vector3 to, bool free)
|
||||
{
|
||||
var prefab = piecePrefabs != null && (int)id < piecePrefabs.Length ? piecePrefabs[(int)id] : null;
|
||||
if (!prefab) { Debug.LogWarning("[Spawner] no prefab for " + id); return null; }
|
||||
var no = Instantiate(prefab, pos, rot);
|
||||
var p = no.GetComponent<BuildPiece>();
|
||||
p.To.Value = to; p.Free.Value = free;
|
||||
no.Spawn(true);
|
||||
return p;
|
||||
}
|
||||
|
||||
// ───────────────────────── fleet ─────────────────────────
|
||||
|
||||
public Vehicle SpawnVehicle(VehicleKind kind, string crew, Vector3 pos, Quaternion rot)
|
||||
{
|
||||
var prefab = vehiclePrefabs[(int)kind];
|
||||
if (!prefab || !Nm.IsServer) return null;
|
||||
var no = Instantiate(prefab, pos, rot);
|
||||
var v = no.GetComponent<Vehicle>();
|
||||
v.Crew.Value = crew;
|
||||
no.Spawn(true);
|
||||
return v;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Spawner.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Spawner.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2821f3c1883ea41429e3f940a1370e86
|
||||
17
Assets/Scripts/Gameplay/StationTerminal.cs
Normal file
17
Assets/Scripts/Gameplay/StationTerminal.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Travel between the stations you've found.</summary>
|
||||
public class StationTerminal : MonoBehaviour, IInteractable
|
||||
{
|
||||
public string Prompt => Loc.T("Travel terminal");
|
||||
public bool CanInteract => TeamState.Instance;
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
Sfx.Play("ui_open");
|
||||
UIRoot.I?.OpenStations();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/StationTerminal.cs.meta
Normal file
2
Assets/Scripts/Gameplay/StationTerminal.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 02d1f38d34638a84f9757ba061b16e8a
|
||||
17
Assets/Scripts/Gameplay/SupplyWall.cs
Normal file
17
Assets/Scripts/Gameplay/SupplyWall.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>The pegboard on the deck where the crew gets its tools. Personal: everyone buys their own.</summary>
|
||||
public class SupplyWall : MonoBehaviour, IInteractable
|
||||
{
|
||||
public string Prompt => Loc.T("Supply wall — tools & gear");
|
||||
public bool CanInteract => TeamState.Instance;
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
Sfx.Play("ui_open");
|
||||
UIRoot.I?.OpenSupply();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/SupplyWall.cs.meta
Normal file
2
Assets/Scripts/Gameplay/SupplyWall.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6c962eaadf265184681219a5dccf25dc
|
||||
67
Assets/Scripts/Gameplay/TeamState.Build.cs
Normal file
67
Assets/Scripts/Gameplay/TeamState.Build.cs
Normal file
@ -0,0 +1,67 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Build mode on the server: placing, moving and removing belts, machines and foundations (full refund on removal, nothing back for company equipment).</summary>
|
||||
public partial class TeamState
|
||||
{
|
||||
[Rpc(SendTo.Server)]
|
||||
public void BuildRpc(byte piece, Vector3 at, Quaternion rot, Vector3 to, RpcParams rpc = default)
|
||||
{
|
||||
var sender = RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp);
|
||||
if (piece >= GameDefs.Pieces.Length) return;
|
||||
var d = GameDefs.Piece((PieceId)piece);
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
bool belt = d.id == PieceId.Belt;
|
||||
double price = belt ? GameDefs.BeltPrice(Vector3.Distance(at, to)) : d.price;
|
||||
bool fits = belt ? BuildRules.CanRun(at, to, out _) : BuildRules.CanPlace(d, at, rot, null, out _);
|
||||
if (d.company || !who || !who.Owns(ToolId.Hammer) || Money.Value < price || !fits) { DeniedRpc(sender); return; }
|
||||
Money.Value -= price;
|
||||
ServerSpawnPiece(d.id, at, belt ? BuildRules.RunRotation(at, to) : rot, to);
|
||||
Save();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void RemovePieceRpc(ulong objectId, RpcParams rpc = default)
|
||||
{
|
||||
var sender = RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp);
|
||||
if (!NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(objectId, out var no)) return;
|
||||
var p = no.GetComponent<BuildPiece>();
|
||||
if (!p) return;
|
||||
if (p.Def.company) { DeniedRpc(sender); AnnounceRpc(Loc.Pack("That's company property: the crew can't remove it.")); return; }
|
||||
if (GameDefs.IsDeck(p.piece) && BuildRules.Riders(p).Count > 0) { DeniedRpc(sender); return; }
|
||||
if (!p.Free.Value) Money.Value += p.Price;
|
||||
no.Despawn(true);
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>A piece goes where it's put, and what stands on a foundation goes with it.</summary>
|
||||
[Rpc(SendTo.Server)]
|
||||
public void MovePieceRpc(ulong objectId, Vector3 at, Quaternion rot, RpcParams rpc = default)
|
||||
{
|
||||
var sender = RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp);
|
||||
if (!NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(objectId, out var no)) return;
|
||||
var p = no.GetComponent<BuildPiece>();
|
||||
if (!p || p.Def.company || p.Run || !BuildRules.CanPlace(p.Def, at, rot, p, out _)) { DeniedRpc(sender); return; }
|
||||
if (GameDefs.IsDeck(p.piece))
|
||||
{
|
||||
var turn = rot * Quaternion.Inverse(p.transform.rotation);
|
||||
var from = p.transform.position;
|
||||
foreach (var r in BuildRules.Riders(p).ToArray())
|
||||
r.MovedRpc(at + turn * (r.transform.position - from), turn * r.transform.rotation);
|
||||
}
|
||||
p.MovedRpc(at, rot);
|
||||
Save();
|
||||
}
|
||||
|
||||
public BuildPiece ServerSpawnPiece(PieceId id, Vector3 at, Quaternion rot, Vector3 to, int setting = -1, bool free = false, float[] state = null)
|
||||
{
|
||||
if (!Spawner.Instance) return null;
|
||||
var p = Spawner.Instance.SpawnPiece(id, at, rot, to, free);
|
||||
if (p && setting >= 0) p.Setting = setting;
|
||||
if (p && state != null && p.TryGetComponent<IPieceState>(out var keeps)) keeps.State = state;
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.Build.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.Build.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: be5039ef5c9dcf440beba623bd72b46e
|
||||
35
Assets/Scripts/Gameplay/TeamState.Cheats.cs
Normal file
35
Assets/Scripts/Gameplay/TeamState.Cheats.cs
Normal file
@ -0,0 +1,35 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Server side of the cheat console (host only): wallet and perks, no strings attached.</summary>
|
||||
public partial class TeamState
|
||||
{
|
||||
public void ServerSetMoney(double value)
|
||||
{
|
||||
if (!IsServer) return;
|
||||
Money.Value = System.Math.Max(0d, value);
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>Set a perk to a level (clamped to its max), with the same side effects as buying it.</summary>
|
||||
public void ServerSetPerk(PerkId id, int level)
|
||||
{
|
||||
if (!IsServer || id >= PerkId.Count) return;
|
||||
var def = GameDefs.Perk(id);
|
||||
int was = Level(id);
|
||||
level = Mathf.Clamp(level, 0, def.maxLevel);
|
||||
if (level == was) return;
|
||||
Perks[(int)id] = (byte)level;
|
||||
if (level > was) PurchasedRpc("Cheats", def.maxLevel > 1 ? Loc.Key(def.nameEn, GameDefs.ToRoman(level)) : Loc.Key(def.nameEn));
|
||||
}
|
||||
|
||||
/// <summary>Hand a player a tool, as if they had bought it.</summary>
|
||||
public void ServerGiveTool(PlayerAgent p, ToolId t)
|
||||
{
|
||||
if (!IsServer || !p) return;
|
||||
p.Owned.Value |= (ushort)(1 << (int)t);
|
||||
SaveCrew(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.Cheats.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.Cheats.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5c356f35c70534748bb892c328601061
|
||||
167
Assets/Scripts/Gameplay/TeamState.Fleet.cs
Normal file
167
Assets/Scripts/Gameplay/TeamState.Fleet.cs
Normal file
@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Machines on the server: each player buys their own, one of each kind, calls it to any garage and tunes it. Paid from the crew wallet.</summary>
|
||||
public partial class TeamState
|
||||
{
|
||||
[Serializable]
|
||||
class VehicleSave
|
||||
{
|
||||
public int kind;
|
||||
public string key;
|
||||
public Vector3 at;
|
||||
public Quaternion turn;
|
||||
public float tank;
|
||||
public int[] tune;
|
||||
public Vector2[] bed;
|
||||
}
|
||||
|
||||
/// <summary>Where a garage puts a machine: its pad, or if it's gone, at the base along the ramp in the first free spot.</summary>
|
||||
Vector3 PadFor(ulong garage, out Quaternion rot)
|
||||
{
|
||||
if (NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(garage, out var no) && no.TryGetComponent<Garage>(out var g))
|
||||
{
|
||||
rot = g.transform.rotation;
|
||||
return g.PadSpot;
|
||||
}
|
||||
var dock = Spawner.Instance ? Spawner.Instance.dock : null;
|
||||
var at = dock ? dock.position : new Vector3(0f, GameDefs.WaterY, -14f);
|
||||
var side = dock ? dock.right : Vector3.right;
|
||||
rot = Quaternion.LookRotation(dock ? dock.forward : Vector3.back);
|
||||
at.y = GameDefs.WaterY + 0.6f;
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
var spot = at + side * (i % 2 == 0 ? i * 2f + 3f : -i * 2f - 3f);
|
||||
if (!Physics.CheckSphere(spot + Vector3.up, 1.6f, 1 << Layers.Vehicle, QueryTriggerInteraction.Ignore)) return spot;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
/// <summary>The shed a machine comes out of: the garage asked, or the base shed.</summary>
|
||||
VehicleShed ShedFor(ulong garage)
|
||||
{
|
||||
if (NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(garage, out var no) && no.TryGetComponent<Garage>(out var g))
|
||||
return g.GetComponent<VehicleShed>();
|
||||
return VehicleShed.Base;
|
||||
}
|
||||
|
||||
/// <summary>Server: the machine waits inside the shed, the door goes up and it drives out onto a free spot on the pad.</summary>
|
||||
bool ServerRollOut(Vehicle v, ulong garage)
|
||||
{
|
||||
var shed = ShedFor(garage);
|
||||
if (!shed || !v) return false;
|
||||
var rot = shed.Facing;
|
||||
// the machine is turned to face out before its length is measured
|
||||
v.ServerPut(v.transform.position, rot);
|
||||
v.Extent(out float tail, out float top, out float bottom);
|
||||
var lift = shed.transform.up * Mathf.Max(0.03f, 0.03f - bottom);
|
||||
var outside = shed.OutsideFor(tail) + lift;
|
||||
var to = outside;
|
||||
var side = shed.transform.right;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
var spot = outside + side * (i == 0 ? 0f : (i % 2 == 1 ? 1f : -1f) * ((i + 1) / 2) * 3.4f);
|
||||
if (!Physics.CheckSphere(spot + shed.transform.up * 0.8f, 1.5f, 1 << Layers.Vehicle, QueryTriggerInteraction.Ignore)) { to = spot; break; }
|
||||
}
|
||||
v.ServerRollOut(shed.InsideFor(tail, top) + lift, to, rot);
|
||||
ShedDoorRpc(garage, v.NetworkObjectId);
|
||||
return true;
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void ShedDoorRpc(ulong garage, ulong vehicle)
|
||||
{
|
||||
var shed = ShedFor(garage);
|
||||
if (shed) shed.Open();
|
||||
// it waits inside out of sight until the door is most of the way up
|
||||
if (NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(vehicle, out var no) && no.TryGetComponent<Vehicle>(out var v))
|
||||
v.HideFor(VehicleShed.Wait * 0.8f);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void BuyVehicleRpc(byte kind, ulong garage, RpcParams rpc = default)
|
||||
{
|
||||
var sender = RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp);
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || !who.ClaimedSave || kind >= (byte)VehicleKind.Count) return;
|
||||
var d = GameDefs.Vehicle((VehicleKind)kind);
|
||||
if (Money.Value < d.price || Vehicle.Mine(d.kind, who.SaveId)) { DeniedRpc(sender); return; }
|
||||
Money.Value -= d.price;
|
||||
var shed = ShedFor(garage);
|
||||
Vector3 at;
|
||||
Quaternion rot;
|
||||
if (shed) { at = shed.Inside; rot = shed.Facing; }
|
||||
else at = PadFor(garage, out rot);
|
||||
var made = Spawner.Instance.SpawnVehicle(d.kind, who.SaveId, at, rot);
|
||||
if (made) ServerRollOut(made, garage);
|
||||
AnnounceRpc(Loc.Pack("A new {0} is waiting at the garage!", Loc.Key(d.nameEn)));
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>Any garage can bring your machine to its pad, wherever it was left.</summary>
|
||||
[Rpc(SendTo.Server)]
|
||||
public void CallVehicleRpc(ulong vehicle, ulong garage, RpcParams rpc = default)
|
||||
{
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || !NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(vehicle, out var no)) return;
|
||||
var v = no.GetComponent<Vehicle>();
|
||||
if (!v || v.HasDriver || v.Crew.Value.ToString() != who.SaveId) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
||||
if (v.RollingOut) return;
|
||||
if (ServerRollOut(v, garage)) return;
|
||||
var at = PadFor(garage, out var rot);
|
||||
v.ServerPut(at, rot);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void TuneVehicleRpc(ulong vehicle, byte tune, RpcParams rpc = default)
|
||||
{
|
||||
var sender = RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp);
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || tune >= (byte)TuneId.Count || !NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(vehicle, out var no)) return;
|
||||
var v = no.GetComponent<Vehicle>();
|
||||
if (!v || v.Crew.Value.ToString() != who.SaveId) { DeniedRpc(sender); return; }
|
||||
var t = (TuneId)tune;
|
||||
int level = v.Level(t);
|
||||
if (level >= GameDefs.Tune(t).prices.Length) { DeniedRpc(sender); return; }
|
||||
double price = GameDefs.TunePrice(v.kind, t, level);
|
||||
if (Money.Value < price) { DeniedRpc(sender); return; }
|
||||
Money.Value -= price;
|
||||
v.Tuned[tune] = (byte)(level + 1);
|
||||
Save();
|
||||
}
|
||||
|
||||
List<VehicleSave> PackVehicles()
|
||||
{
|
||||
var list = new List<VehicleSave>();
|
||||
foreach (var v in Vehicle.All)
|
||||
{
|
||||
if (!v || !v.IsSpawned) continue;
|
||||
var s = new VehicleSave { kind = (int)v.kind, key = v.Crew.Value.ToString(), at = v.transform.position, turn = v.transform.rotation, tank = v.Tank.Value };
|
||||
s.tune = new int[v.Tuned.Count];
|
||||
for (int i = 0; i < s.tune.Length; i++) s.tune[i] = v.Tuned[i];
|
||||
s.bed = new Vector2[v.Bed.Count];
|
||||
for (int i = 0; i < s.bed.Length; i++) s.bed[i] = v.Bed[i];
|
||||
list.Add(s);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
void UnpackVehicles(List<VehicleSave> list)
|
||||
{
|
||||
if (list == null || !Spawner.Instance) return;
|
||||
foreach (var s in list)
|
||||
{
|
||||
if (s.kind < 0 || s.kind >= (int)VehicleKind.Count) continue;
|
||||
var v = Spawner.Instance.SpawnVehicle((VehicleKind)s.kind, s.key, s.at, s.turn);
|
||||
if (!v) continue;
|
||||
v.Tank.Value = s.tank;
|
||||
if (s.tune != null) for (int i = 0; i < s.tune.Length && i < v.Tuned.Count; i++) v.Tuned[i] = (byte)s.tune[i];
|
||||
if (s.bed != null) foreach (var b in s.bed) v.Bed.Add(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.Fleet.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.Fleet.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: efc324600d5b59a41951847f7cec8b0c
|
||||
45
Assets/Scripts/Gameplay/TeamState.Mow.cs
Normal file
45
Assets/Scripts/Gameplay/TeamState.Mow.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public partial class TeamState
|
||||
{
|
||||
const int MowChunk = 16000;
|
||||
MemoryStream _mowIn;
|
||||
|
||||
/// <summary>Server: a player joined a game in progress. Hand them everything that has been cut.</summary>
|
||||
public void ServerSendMow(ulong to)
|
||||
{
|
||||
if (to != NetworkManager.ServerClientId) StartCoroutine(SendMow(to));
|
||||
}
|
||||
|
||||
IEnumerator SendMow(ulong to)
|
||||
{
|
||||
var data = MowMap.Serialize();
|
||||
int count = Mathf.Max(1, Mathf.CeilToInt(data.Length / (float)MowChunk));
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (!NetworkManager.ConnectedClients.ContainsKey(to)) yield break;
|
||||
int at = i * MowChunk, len = Mathf.Min(MowChunk, data.Length - at);
|
||||
var chunk = new byte[len];
|
||||
System.Buffer.BlockCopy(data, at, chunk, 0, len);
|
||||
MowChunkRpc(chunk, i, count, RpcTarget.Single(to, RpcTargetUse.Temp));
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams)]
|
||||
void MowChunkRpc(byte[] chunk, int index, int count, RpcParams p = default)
|
||||
{
|
||||
if (index == 0) _mowIn = new MemoryStream();
|
||||
if (_mowIn == null) return;
|
||||
_mowIn.Write(chunk, 0, chunk.Length);
|
||||
if (index < count - 1) return;
|
||||
MowMap.Merge(_mowIn.ToArray());
|
||||
_mowIn = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.Mow.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.Mow.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d70e33e87bdede84a90d18cc7d3b5053
|
||||
83
Assets/Scripts/Gameplay/TeamState.Sectors.cs
Normal file
83
Assets/Scripts/Gameplay/TeamState.Sectors.cs
Normal file
@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using Unity.Collections;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public partial class TeamState
|
||||
{
|
||||
/// <summary>Sector, what it paid.</summary>
|
||||
public static event Action<int, double> SectorClosed;
|
||||
/// <summary>Who, which landmark, what it paid.</summary>
|
||||
public static event Action<string, int, double> MarkFound;
|
||||
|
||||
float _mownAt;
|
||||
|
||||
void WatchSectors()
|
||||
{
|
||||
MowMap.SectorDone += OnSectorDone;
|
||||
Found.OnListChanged += _ => { if (Landmarks.Instance) Landmarks.Instance.Refresh(); Changed?.Invoke(); };
|
||||
if (Landmarks.Instance) Landmarks.Instance.Refresh();
|
||||
}
|
||||
|
||||
void UnwatchSectors() => MowMap.SectorDone -= OnSectorDone;
|
||||
|
||||
/// <summary>Each peer finishes sectors for itself, a little apart: whoever gets there first tells the host.</summary>
|
||||
void OnSectorDone(int id)
|
||||
{
|
||||
if (IsServer) ServerCloseSector(id);
|
||||
else SectorDoneRpc(id);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
void SectorDoneRpc(int id, RpcParams rpc = default) => ServerCloseSector(id);
|
||||
|
||||
void ServerCloseSector(int id)
|
||||
{
|
||||
if (id < 0 || id >= HexGrid.Cells || !MowMap.Claim(id)) return;
|
||||
double pay = GameDefs.SectorBonus(Level(PerkId.RegionBonus)) * Crops.Pays(Crops.At(id));
|
||||
Money.Value += pay;
|
||||
Closed.Value++;
|
||||
SectorClosedRpc(id, pay);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void SectorClosedRpc(int id, double pay)
|
||||
{
|
||||
MowMap.Close(id);
|
||||
SectorClosed?.Invoke(id, pay);
|
||||
}
|
||||
|
||||
void TickSectors()
|
||||
{
|
||||
if (Time.time < _mownAt) return;
|
||||
_mownAt = Time.time + 1f;
|
||||
Mown.Value = MowMap.MownArea();
|
||||
}
|
||||
|
||||
// ───────────────────────── stakes & survey points ─────────────────────────
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void ClaimMarkRpc(int id, RpcParams rpc = default)
|
||||
{
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || id < 0 || id >= Landmarks.Count || Found.Contains(id)) return;
|
||||
if ((who.transform.position - Landmarks.Spot(id)).sqrMagnitude > 64f) return;
|
||||
double pay = Landmarks.Pay(id);
|
||||
Found.Add(id);
|
||||
Money.Value += pay;
|
||||
MarkFoundRpc(who.DisplayName, id, pay);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void MarkFoundRpc(FixedString64Bytes who, int id, double pay) => MarkFound?.Invoke(who.ToString(), id, pay);
|
||||
|
||||
public int FoundCount(bool points)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (int id in Found) if (Landmarks.IsPoint(id) == points) n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.Sectors.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.Sectors.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ea8513069f42f1b45ba2c56a3b70a4f1
|
||||
114
Assets/Scripts/Gameplay/TeamState.Stations.cs
Normal file
114
Assets/Scripts/Gameplay/TeamState.Stations.cs
Normal file
@ -0,0 +1,114 @@
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>The stations the crew has found, travel between them, and who isn't welcome.</summary>
|
||||
public partial class TeamState
|
||||
{
|
||||
/// <summary>Stations found, not counting the base.</summary>
|
||||
public NetworkList<byte> Opened;
|
||||
|
||||
List<string> _banned = new List<string>();
|
||||
|
||||
public bool StationOpen(int i) => i == 0 || (Opened != null && Opened.Contains((byte)i));
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void OpenStationRpc(int i, RpcParams rpc = default)
|
||||
{
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || i <= 0 || i >= Stations.Count || StationOpen(i)) return;
|
||||
if ((who.transform.position - Stations.Spot(i)).sqrMagnitude > 3600f) return;
|
||||
Opened.Add((byte)i);
|
||||
AnnounceRpc(Loc.Pack("{0} found {1} Station!", who.DisplayName, Stations.Names[i]));
|
||||
Save();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void TravelRpc(int i, RpcParams rpc = default)
|
||||
{
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || i < 0 || i >= Stations.Count) return;
|
||||
if (who.Driving.Value || !StationOpen(i) || i == Stations.Nearest(who.transform.position) || Money.Value < GameDefs.TravelPrice)
|
||||
{
|
||||
DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp));
|
||||
return;
|
||||
}
|
||||
Money.Value -= GameDefs.TravelPrice;
|
||||
who.ArriveRpc(Stations.Arrival(i));
|
||||
}
|
||||
|
||||
/// <summary>Host: send someone away, for good if they are banned.</summary>
|
||||
public void ServerKick(ulong client, bool ban)
|
||||
{
|
||||
if (!IsServer || client == NetworkManager.ServerClientId) return;
|
||||
var who = PlayerOf(client);
|
||||
if (ban && who && who.ClaimedSave && !_banned.Contains(who.SaveId)) _banned.Add(who.SaveId);
|
||||
NetworkManager.DisconnectClient(client, ban ? Loc.Pack("You were banned from this game") : Loc.Pack("The host asked you to leave"));
|
||||
Save();
|
||||
}
|
||||
|
||||
public bool Banned(string key) => _banned.Contains(key);
|
||||
|
||||
/// <summary>The depots of the far stations: a new game has them, and an older save gets them now.</summary>
|
||||
void ServerSpawnStations()
|
||||
{
|
||||
for (int i = 1; i < Stations.Count; i++) ServerSpawnPiece(PieceId.Depot, Stations.Spot(i), Stations.Turn(i), Vector3.zero, -1, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Eight low intakes on the ground against the sides of the base deck, two on each side, so a belt from the meadow can
|
||||
/// end at the base without climbing up top. They sit between the ladders, clear of the ramp, backs to the deck.
|
||||
/// A new game has them, and an older save gets them now (the tall depots that stood there before go).
|
||||
/// </summary>
|
||||
void ServerSpawnIntakes()
|
||||
{
|
||||
foreach (var spot in IntakeSpots)
|
||||
{
|
||||
// straight out from the side it stands on, back square to the deck
|
||||
var outward = Mathf.Abs(spot.x) > Mathf.Abs(spot.z) ? new Vector3(Mathf.Sign(spot.x), 0f, 0f) : new Vector3(0f, 0f, Mathf.Sign(spot.z));
|
||||
ServerSpawnPiece(PieceId.Intake, Planet.Surface(spot), Quaternion.LookRotation(outward, Vector3.up), Vector3.zero, -1, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A save from stage 18 has tall depots round the foot of the deck: they make way for the intakes.</summary>
|
||||
void ServerSwapIntakes()
|
||||
{
|
||||
foreach (var p in BuildPiece.All.ToArray())
|
||||
{
|
||||
if (!p || p.piece != PieceId.Depot || Planet.Altitude(p.transform.position) > 0.6f) continue;
|
||||
var flat = new Vector2(p.transform.position.x, p.transform.position.z);
|
||||
foreach (var old in OldIntakeSpots)
|
||||
if ((flat - new Vector2(old.x, old.z)).magnitude < 2.5f) { p.NetworkObject.Despawn(true); break; }
|
||||
}
|
||||
ServerSpawnIntakes();
|
||||
}
|
||||
|
||||
/// <summary>Saves from the first stage-19 build have the intakes turned 45° off the deck: they are set again.</summary>
|
||||
void ServerRespawnIntakes()
|
||||
{
|
||||
foreach (var p in BuildPiece.All.ToArray())
|
||||
if (p && p.piece == PieceId.Intake) p.NetworkObject.Despawn(true);
|
||||
ServerSpawnIntakes();
|
||||
}
|
||||
|
||||
/// <summary>The deck runs ±9 m; an intake is 1.5 m deep, so its middle is 9.77 m out, 6 m either side of each edge's middle.</summary>
|
||||
public static readonly Vector3[] IntakeSpots =
|
||||
{
|
||||
new Vector3(-6f, 0f, 9.77f), new Vector3(6f, 0f, 9.77f),
|
||||
new Vector3(-6f, 0f, -9.77f), new Vector3(6f, 0f, -9.77f),
|
||||
new Vector3(9.77f, 0f, -6f), new Vector3(9.77f, 0f, 6f),
|
||||
new Vector3(-9.77f, 0f, -6f), new Vector3(-9.77f, 0f, 6f),
|
||||
};
|
||||
|
||||
static readonly Vector3[] OldIntakeSpots =
|
||||
{
|
||||
new Vector3(-6f, 0f, 11f), new Vector3(6f, 0f, 11f),
|
||||
new Vector3(-6f, 0f, -11f), new Vector3(6f, 0f, -11f),
|
||||
new Vector3(11f, 0f, -6f), new Vector3(11f, 0f, 6f),
|
||||
new Vector3(-11f, 0f, -6f), new Vector3(-11f, 0f, 6f),
|
||||
};
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.Stations.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.Stations.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 69b4a47347a1d6347ba84b18077d51b5
|
||||
276
Assets/Scripts/Gameplay/TeamState.Weather.cs
Normal file
276
Assets/Scripts/Gameplay/TeamState.Weather.cs
Normal file
@ -0,0 +1,276 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public enum WeatherKind : byte { Clear, Clouds, Rain, AcidRain, Wind, Storm, Meteors, Count }
|
||||
|
||||
/// <summary>
|
||||
/// Herbaria-7's weather, decided by the host and the same for everyone. Spells of a few minutes each: clear, cloud, rain, acid
|
||||
/// rain (it scorches a little of the meadow, which is gone for good and pays nothing), wind with twisters that tear up the
|
||||
/// grass in a line and throw the crew about, thunderstorms, and on clear nights a meteor shower. Now and then a flying saucer
|
||||
/// comes down, draws a crop circle in the meadow and leaves the crew a tip for it.
|
||||
/// </summary>
|
||||
public partial class TeamState
|
||||
{
|
||||
public readonly NetworkVariable<byte> Weather = new NetworkVariable<byte>();
|
||||
/// <summary>A twister: where it set off, which way, and when (server time; 0 when there is none).</summary>
|
||||
public readonly NetworkVariable<Vector3> TwisterFrom = new NetworkVariable<Vector3>(), TwisterDir = new NetworkVariable<Vector3>();
|
||||
public readonly NetworkVariable<double> TwisterAt = new NetworkVariable<double>();
|
||||
/// <summary>The saucer: the spot it comes down over and when it set off.</summary>
|
||||
public readonly NetworkVariable<Vector3> UfoSpot = new NetworkVariable<Vector3>();
|
||||
public readonly NetworkVariable<double> UfoAt = new NetworkVariable<double>();
|
||||
|
||||
public const float TwisterLife = 70f, TwisterSpeed = 3.6f, TwisterRadius = 3.2f;
|
||||
/// <summary>Saucer timeline in seconds: coming down, drawing, leaving.</summary>
|
||||
public const float UfoArrive = 7f, UfoDraw = 22f, UfoLeave = 6f;
|
||||
|
||||
public WeatherKind WeatherNow => (WeatherKind)Weather.Value;
|
||||
public double Now => ClockOverride != null ? ClockOverride() : NetworkManager ? NetworkManager.ServerTime.Time : 0d;
|
||||
/// <summary>The trailer's clock: the time of the frames it writes, not of the wall, so a twister or a saucer moves
|
||||
/// at its own pace however long each frame takes to render.</summary>
|
||||
public static System.Func<double> ClockOverride;
|
||||
public bool TwisterOn => TwisterAt.Value > 0d && Now - TwisterAt.Value < TwisterLife;
|
||||
public bool UfoOn => UfoAt.Value > 0d && Now - UfoAt.Value < UfoArrive + UfoDraw + UfoLeave;
|
||||
|
||||
double _weatherUntil, _nextBurn, _nextUfoRoll, _ufoCooldown;
|
||||
bool _ufoPaid;
|
||||
|
||||
/// <summary>Where the twister is at a moment: a wandering line across the meadow, the same on every machine.</summary>
|
||||
public Vector3 TwisterPos(double t)
|
||||
{
|
||||
float s = (float)(t - TwisterAt.Value);
|
||||
var from = TwisterFrom.Value;
|
||||
var up = Planet.Up(from);
|
||||
var dir = TwisterDir.Value;
|
||||
var side = Vector3.Cross(up, dir).normalized;
|
||||
var p = from + dir * (s * TwisterSpeed) + side * (Mathf.Sin(s * 0.21f) * 9f + Mathf.Sin(s * 0.53f) * 3f);
|
||||
return Planet.Surface(p);
|
||||
}
|
||||
|
||||
static readonly WeatherKind[] Bag = { WeatherKind.Clear, WeatherKind.Clear, WeatherKind.Clear, WeatherKind.Clouds, WeatherKind.Clouds, WeatherKind.Rain, WeatherKind.Rain, WeatherKind.Wind, WeatherKind.AcidRain, WeatherKind.Storm };
|
||||
|
||||
void TickWeather()
|
||||
{
|
||||
double now = Now;
|
||||
if (now >= _weatherUntil)
|
||||
{
|
||||
var next = Bag[Random.Range(0, Bag.Length)];
|
||||
// a clear night is a meteor night half the time
|
||||
if (next == WeatherKind.Clear && Sun.Height(Planet.Up(Spawner.Instance ? Spawner.Instance.transform.position : Vector3.up)) < -0.1f && Random.value < 0.5f) next = WeatherKind.Meteors;
|
||||
// the first minutes of a new game are always fine
|
||||
if (Time.timeSinceLevelLoad < 240f) next = WeatherKind.Clear;
|
||||
ServerSetWeather(next, Random.Range(180f, 360f));
|
||||
}
|
||||
var kind = WeatherNow;
|
||||
if ((kind == WeatherKind.Wind || kind == WeatherKind.Storm) && !TwisterOn && Random.value < Time.deltaTime / 40f) ServerTwister(null);
|
||||
if (kind == WeatherKind.AcidRain && now >= _nextBurn) { _nextBurn = now + 1.5d; ServerBurn(); }
|
||||
if (TwisterOn) ServerTwisterTick();
|
||||
if (UfoOn) ServerUfoTick();
|
||||
else if (now >= _nextUfoRoll && now >= _ufoCooldown && Time.timeSinceLevelLoad > 300f)
|
||||
{
|
||||
_nextUfoRoll = now + 60d;
|
||||
bool night = DayNight.Dark > 0.5f;
|
||||
if (Random.value < (night ? 0.08f : 0.03f)) ServerUfo(null);
|
||||
}
|
||||
}
|
||||
|
||||
public void ServerSetWeather(WeatherKind k, float seconds)
|
||||
{
|
||||
if (!IsServer) return;
|
||||
Weather.Value = (byte)k;
|
||||
_weatherUntil = Now + seconds;
|
||||
if (k != WeatherKind.Clear && k != WeatherKind.Clouds) WeatherNewsRpc((byte)k);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void WeatherNewsRpc(byte kind)
|
||||
{
|
||||
switch ((WeatherKind)kind)
|
||||
{
|
||||
case WeatherKind.Rain: Assistant.Say("asst_rain"); Hud.Toast(Loc.T("Rain. The solar panels give less while it lasts."), Hud.ToastKind.Info); break;
|
||||
case WeatherKind.AcidRain: Assistant.Say("asst_acid"); Hud.Toast(Loc.T("Acid rain! It scorches the meadow here and there: that grass is gone and pays nothing."), Hud.ToastKind.Warn); break;
|
||||
case WeatherKind.Wind: Assistant.Say("asst_wind"); Hud.Toast(Loc.T("The wind is getting up. Watch out for twisters."), Hud.ToastKind.Warn); break;
|
||||
case WeatherKind.Storm: Assistant.Say("asst_storm"); Hud.Toast(Loc.T("Thunderstorm! Dark skies, weak sun, twisters about."), Hud.ToastKind.Warn); break;
|
||||
case WeatherKind.Meteors: Assistant.Say("asst_meteors"); Hud.Toast(Loc.T("A meteor shower tonight. Look up!"), Hud.ToastKind.Info); break;
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── acid rain ─────────────────────────
|
||||
|
||||
static readonly List<Vector3> s_burns = new List<Vector3>();
|
||||
|
||||
void ServerBurn()
|
||||
{
|
||||
s_burns.Clear();
|
||||
foreach (var p in PlayerAgent.All)
|
||||
{
|
||||
if (!p) continue;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
var at = Planet.Surface(p.transform.position + Random.insideUnitSphere * 26f);
|
||||
if (OnDeck(at) || MowMap.Yield(at) < 0.2f) continue;
|
||||
s_burns.Add(at);
|
||||
}
|
||||
}
|
||||
if (s_burns.Count > 0) BurnRpc(s_burns.ToArray());
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void BurnRpc(Vector3[] spots)
|
||||
{
|
||||
foreach (var at in spots)
|
||||
{
|
||||
var up = Planet.Up(at);
|
||||
var side = Vector3.Cross(up, Vector3.forward).normalized * 0.4f;
|
||||
MowMap.Cut(at - side, at + side, 1.1f);
|
||||
Fx.Smoke(at + up * 0.3f, 0.5f);
|
||||
WeatherFx.Sizzle(at);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── twisters ─────────────────────────
|
||||
|
||||
/// <summary>Server: a twister sets off toward the crew, from a spot ahead of someone (or where it's told).</summary>
|
||||
public void ServerTwister(Vector3? at)
|
||||
{
|
||||
if (!IsServer || PlayerAgent.All.Count == 0) return;
|
||||
var who = PlayerAgent.All[Random.Range(0, PlayerAgent.All.Count)];
|
||||
var target = at ?? who.transform.position;
|
||||
var up = Planet.Up(target);
|
||||
var away = Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized;
|
||||
var from = Planet.Surface(target + away * (at.HasValue ? 0f : 60f));
|
||||
TwisterFrom.Value = from;
|
||||
TwisterDir.Value = at.HasValue ? Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized : -away;
|
||||
TwisterAt.Value = Now;
|
||||
TwisterNewsRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void TwisterNewsRpc() { Assistant.Say("asst_twister"); Hud.Toast(Loc.T("A twister is coming! It rips up the grass in its path and throws you about."), Hud.ToastKind.Warn); }
|
||||
|
||||
static readonly Collider[] s_hits = new Collider[32];
|
||||
|
||||
/// <summary>Server: loose bundles near the twister are lifted and spun out.</summary>
|
||||
void ServerTwisterTick()
|
||||
{
|
||||
var at = TwisterPos(Now);
|
||||
var up = Planet.Up(at);
|
||||
int n = Physics.OverlapSphereNonAlloc(at + up * 2f, TwisterRadius + 2f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var rb = s_hits[i].attachedRigidbody;
|
||||
if (!rb || rb.isKinematic) continue;
|
||||
var off = Vector3.ProjectOnPlane(rb.position - at, up);
|
||||
var swirl = Vector3.Cross(up, off.normalized) * 9f;
|
||||
rb.AddForce((swirl + up * 14f - off * 1.5f) * rb.mass, ForceMode.Force);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── the saucer ─────────────────────────
|
||||
|
||||
/// <summary>Server: a saucer comes down over unmown meadow near someone.</summary>
|
||||
public void ServerUfo(Vector3? at)
|
||||
{
|
||||
if (!IsServer || PlayerAgent.All.Count == 0) return;
|
||||
Vector3 spot = default;
|
||||
bool found = false;
|
||||
if (at.HasValue) { spot = Planet.Surface(at.Value); found = true; }
|
||||
for (int tries = 0; tries < 30 && !found; tries++)
|
||||
{
|
||||
var who = PlayerAgent.All[Random.Range(0, PlayerAgent.All.Count)];
|
||||
var up = Planet.Up(who.transform.position);
|
||||
var p = Planet.Surface(who.transform.position + Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized * Random.Range(25f, 50f));
|
||||
if (OnDeck(p) || MowMap.Yield(p) < 0.6f) continue;
|
||||
spot = p; found = true;
|
||||
}
|
||||
if (!found) return;
|
||||
UfoSpot.Value = spot;
|
||||
UfoAt.Value = Now;
|
||||
_ufoPaid = false;
|
||||
_ufoCooldown = Now + 900d;
|
||||
UfoNewsRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void UfoNewsRpc() { Assistant.Say("asst_ufo"); Hud.Toast(Loc.T("Something is coming down out of the sky…"), Hud.ToastKind.Warn); }
|
||||
|
||||
void ServerUfoTick()
|
||||
{
|
||||
if (_ufoPaid || Now - UfoAt.Value < UfoArrive + UfoDraw) return;
|
||||
_ufoPaid = true;
|
||||
double tip = System.Math.Round(System.Math.Max(150d, Shipped.Value * 0.03d));
|
||||
Money.Value += tip;
|
||||
AnnounceRpc(Loc.Pack("The visitors liked the meadow: they left {0} by their crop circle.", UIK.Money(tip)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The crop circle: rings and spokes in the saucer's own frame, as strokes from the centre outward. Every peer cuts the
|
||||
/// part of it that the drawing time has reached, so it appears line by line under the beam.
|
||||
/// </summary>
|
||||
public static void CropCircle(Vector3 centre, int seed, float upTo, ref int done)
|
||||
{
|
||||
var strokes = CircleStrokes(centre, seed);
|
||||
int last = Mathf.Min(strokes.Count, Mathf.CeilToInt(upTo * strokes.Count));
|
||||
for (; done < last; done++)
|
||||
{
|
||||
var s = strokes[done];
|
||||
MowMap.Cut(s.a, s.b, s.w);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where the drawing has got to: the saucer drifts over it.</summary>
|
||||
public static Vector3 CircleAt(Vector3 centre, int seed, float upTo)
|
||||
{
|
||||
var strokes = CircleStrokes(centre, seed);
|
||||
int i = Mathf.Clamp(Mathf.CeilToInt(upTo * strokes.Count) - 1, 0, strokes.Count - 1);
|
||||
return (strokes[i].a + strokes[i].b) * 0.5f;
|
||||
}
|
||||
|
||||
public struct Stroke { public Vector3 a, b; public float w; }
|
||||
static readonly Dictionary<int, List<Stroke>> s_circles = new Dictionary<int, List<Stroke>>();
|
||||
|
||||
static List<Stroke> CircleStrokes(Vector3 centre, int seed)
|
||||
{
|
||||
if (s_circles.TryGetValue(seed, out var list)) return list;
|
||||
list = new List<Stroke>();
|
||||
var rng = new System.Random(seed);
|
||||
var up = Planet.Up(centre);
|
||||
var x = Vector3.ProjectOnPlane(Vector3.forward, up).normalized;
|
||||
if (x.sqrMagnitude < 0.1f) x = Vector3.ProjectOnPlane(Vector3.right, up).normalized;
|
||||
var z = Vector3.Cross(x, up);
|
||||
Vector3 At(float r, float a) => Planet.Surface(centre + (x * Mathf.Cos(a) + z * Mathf.Sin(a)) * r);
|
||||
// the middle: a filled disc as a tight spiral
|
||||
for (float a = 0f, r = 0.3f; r < 2.4f; a += 0.5f, r += 0.06f) list.Add(new Stroke { a = At(r, a), b = At(r + 0.06f, a + 0.5f), w = 0.9f });
|
||||
int spokes = 4 + rng.Next(5);
|
||||
float[] rings = { 4f + (float)rng.NextDouble(), 7f + (float)rng.NextDouble() * 1.5f, 10f + (float)rng.NextDouble() * 2f };
|
||||
foreach (float r in rings)
|
||||
{
|
||||
int segs = Mathf.CeilToInt(r * 6f);
|
||||
for (int i = 0; i < segs; i++) list.Add(new Stroke { a = At(r, i * Mathf.PI * 2f / segs), b = At(r, (i + 1) * Mathf.PI * 2f / segs), w = 0.9f });
|
||||
}
|
||||
for (int s = 0; s < spokes; s++)
|
||||
{
|
||||
float a = s * Mathf.PI * 2f / spokes;
|
||||
for (float r = 2.4f; r < rings[2]; r += 1f) list.Add(new Stroke { a = At(r, a), b = At(Mathf.Min(rings[2], r + 1f), a), w = 0.7f });
|
||||
// a little satellite circle at the end of every other spoke
|
||||
if (s % 2 == 0)
|
||||
{
|
||||
var c = rings[2] + 2.2f;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
float b0 = i * Mathf.PI * 0.2f, b1 = (i + 1) * Mathf.PI * 0.2f;
|
||||
var cc = At(c, a);
|
||||
var cu = Planet.Up(cc);
|
||||
var cx = Vector3.ProjectOnPlane(x, cu).normalized;
|
||||
var cz = Vector3.Cross(cx, cu);
|
||||
list.Add(new Stroke { a = Planet.Surface(cc + (cx * Mathf.Cos(b0) + cz * Mathf.Sin(b0)) * 1.4f), b = Planet.Surface(cc + (cx * Mathf.Cos(b1) + cz * Mathf.Sin(b1)) * 1.4f), w = 0.8f });
|
||||
}
|
||||
}
|
||||
}
|
||||
s_circles[seed] = list;
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.Weather.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.Weather.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1aa910ce113b36e48afe9a6c9908af86
|
||||
423
Assets/Scripts/Gameplay/TeamState.cs
Normal file
423
Assets/Scripts/Gameplay/TeamState.cs
Normal file
@ -0,0 +1,423 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Collections;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Shared, server-owned crew progress: wallet, kilos shipped to Earth (= how much of Herbaria-7 is mown), the upgrade
|
||||
/// matrix, deck tiles and the save game. Tools, belt slots and gear are personal, and the host's save remembers them.
|
||||
/// </summary>
|
||||
public partial class TeamState : NetworkBehaviour
|
||||
{
|
||||
public static TeamState Instance { get; private set; }
|
||||
|
||||
public readonly NetworkVariable<double> Money = new NetworkVariable<double>();
|
||||
public readonly NetworkVariable<double> Shipped = new NetworkVariable<double>();
|
||||
/// <summary>Square metres mown, as the host counts them.</summary>
|
||||
public readonly NetworkVariable<double> Mown = new NetworkVariable<double>();
|
||||
/// <summary>Sectors mown clean.</summary>
|
||||
public readonly NetworkVariable<int> Closed = new NetworkVariable<int>();
|
||||
public NetworkList<byte> Perks;
|
||||
public NetworkList<int> Tiles;
|
||||
/// <summary>Stakes and survey points the crew has done.</summary>
|
||||
public NetworkList<int> Found;
|
||||
|
||||
public static event Action<double, double> MoneyChanged;
|
||||
public static event Action<string, string> Purchased; // who, what
|
||||
/// <summary>Added to the server clock to give the time of day.</summary>
|
||||
public readonly NetworkVariable<float> DayOffset = new NetworkVariable<float>();
|
||||
/// <summary>How big the ball is (<see cref="Difficulty"/>): the host's save says, everyone builds on the same one.</summary>
|
||||
public readonly NetworkVariable<byte> Size = new NetworkVariable<byte>();
|
||||
public static event Action<string> Announcement;
|
||||
public static event Action<Vector3, double, double> Deposited; // where, money, kilos
|
||||
public static event Action Changed;
|
||||
public static event Action TilesChanged;
|
||||
|
||||
[Serializable] class PieceSave { public int id, cfg; public bool free; public Vector3 at, to; public Quaternion turn; public float[] state; }
|
||||
[Serializable] class CrewSave { public string key; public int owned, slots, current = 255; public int[] belt; public float[] bins; }
|
||||
[Serializable] class CargoSave { public int kind; public float kg; public Vector3 at; }
|
||||
[Serializable]
|
||||
class SaveData
|
||||
{
|
||||
/// <summary>0: pieces stood on the old 1 m grid.</summary>
|
||||
public int ver;
|
||||
/// <summary>How big the ball is: 0 the whole planet (every save from before there was a choice), 1 half, 2 a third.</summary>
|
||||
public int level;
|
||||
public double money, shipped, mown;
|
||||
/// <summary>Time of day: the first morning begins here.</summary>
|
||||
public float day = 0.75f;
|
||||
public int[] perks;
|
||||
public int[] tiles;
|
||||
public int[] found;
|
||||
public int[] stations;
|
||||
public List<string> banned = new List<string>();
|
||||
public List<PieceSave> pieces = new List<PieceSave>();
|
||||
public List<CrewSave> crew = new List<CrewSave>();
|
||||
public List<CargoSave> cargo = new List<CargoSave>();
|
||||
public List<VehicleSave> vehicles = new List<VehicleSave>();
|
||||
}
|
||||
|
||||
static readonly long[][] OldFleet = { new long[] { 1000 }, new long[] { 6000 }, new long[] { 250, 600, 1500 }, new long[] { 200, 500, 1200 }, new long[] { 150, 400 } };
|
||||
|
||||
/// <summary>A crew that leaves more lying around than this loses the rest on a restart.</summary>
|
||||
const int MaxSavedBundles = 4000;
|
||||
|
||||
List<CrewSave> _crew = new List<CrewSave>();
|
||||
|
||||
void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
Perks = new NetworkList<byte>();
|
||||
Tiles = new NetworkList<int>();
|
||||
Found = new NetworkList<int>();
|
||||
Opened = new NetworkList<byte>();
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
Instance = this;
|
||||
Money.OnValueChanged += (a, b) => { MoneyChanged?.Invoke(a, b); Changed?.Invoke(); };
|
||||
Perks.OnListChanged += _ => Changed?.Invoke();
|
||||
Opened.OnListChanged += _ => Changed?.Invoke();
|
||||
Tiles.OnListChanged += _ => { TilesChanged?.Invoke(); Changed?.Invoke(); };
|
||||
if (!IsServer)
|
||||
{
|
||||
Difficulties.Apply((Difficulty)Size.Value);
|
||||
MowMap.Reset(); // the host sends what has been cut
|
||||
}
|
||||
WatchSectors();
|
||||
if (IsServer)
|
||||
{
|
||||
for (int i = 0; i < (int)PerkId.Count; i++) Perks.Add(0);
|
||||
Load();
|
||||
}
|
||||
TilesChanged?.Invoke();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
if (Instance == this) Instance = null;
|
||||
UnwatchSectors();
|
||||
}
|
||||
|
||||
// ───────────────────────── queries ─────────────────────────
|
||||
|
||||
public int Level(PerkId id) => Perks != null && (int)id < Perks.Count ? Perks[(int)id] : 0;
|
||||
public bool Has(PerkId id) => Level(id) > 0;
|
||||
|
||||
public bool PerkAvailable(PerkDef d)
|
||||
{
|
||||
foreach (var r in d.requires) if (Level(r) < d.requireLevel) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Matrix installs so far, out of <see cref="TotalInstalls"/>; the uplink in the middle comes free.</summary>
|
||||
public int Installs
|
||||
{
|
||||
get { int n = 1; foreach (var d in GameDefs.Perks) n += Level(d.id); return n; }
|
||||
}
|
||||
|
||||
public static int TotalInstalls
|
||||
{
|
||||
get { int n = 1; foreach (var d in GameDefs.Perks) n += d.maxLevel; return n; }
|
||||
}
|
||||
|
||||
public double Mown01 => Mown.Value / GameDefs.PlanetArea;
|
||||
|
||||
public float ToolCap(ToolId t) => GameDefs.IsBlade(t) ? GameDefs.ToolCap(t, GameDefs.HasBinPerk(t) ? Level(GameDefs.BinPerk(t)) : 0, Level(PerkId.Compactor)) : 0f;
|
||||
|
||||
/// <summary>The strip this tool cuts right now, in metres.</summary>
|
||||
public float ToolWidth(ToolId t) => GameDefs.Tool(t).width * (1f + GameDefs.WidthBonus(Level(PerkId.WiderBlades))) * (1f + Level(PerkId.DeepSwath) * 0.06f) * (Has(PerkId.WhetSteel) ? 1.1f : 1f);
|
||||
|
||||
public float ToolDepthMul => (1f + Level(PerkId.DeepSwath) * 0.12f) * (Has(PerkId.WhetSteel) ? 1.1f : 1f);
|
||||
|
||||
public float ToolReach => GameDefs.ToolReach + Level(PerkId.LongHandles) * 0.75f + (Has(PerkId.WhetSteel) ? 0.5f : 0f);
|
||||
|
||||
public float BundleSeconds => GameDefs.BundleSeconds(Level(PerkId.QuickTwine), Level(PerkId.ExpressDepot));
|
||||
|
||||
public float PayoutMul => GameDefs.PayoutMul(Level(PerkId.EarthPrices), Level(PerkId.GreenExchange));
|
||||
|
||||
public double ToolPrice(ToolDef d) => d.id == ToolId.Hammer ? d.price : Math.Round(d.price * (double)GameDefs.ToolPriceMul(Level(PerkId.SupplyDeals)), 2);
|
||||
|
||||
public bool HasTile(int tx, int tz) => Tiles != null && Tiles.Contains(PackTile(tx, tz));
|
||||
public bool OnDeck(Vector3 world) => Planet.InNorthCap(world) && HasTile(TileOf(world.x), TileOf(world.z));
|
||||
|
||||
public static int TileOf(float w) => Mathf.FloorToInt((w + GameDefs.TileSize * 0.5f) / GameDefs.TileSize);
|
||||
public static int PackTile(int tx, int tz) => ((tx + 512) << 10) | (tz + 512);
|
||||
public static Vector2Int UnpackTile(int p) => new Vector2Int((p >> 10) - 512, (p & 1023) - 512);
|
||||
public static Vector3 TileCenter(int tx, int tz) => new Vector3(tx * GameDefs.TileSize, 0f, tz * GameDefs.TileSize);
|
||||
|
||||
// ───────────────────────── server: grass & money ─────────────────────────
|
||||
|
||||
/// <summary>Server: this much grass reached a depot. Pays at once and it is on its way to Earth.</summary>
|
||||
public double ServerDeposit(float kg, CargoKind kind, Vector3 at)
|
||||
{
|
||||
if (!IsServer || kg <= 0f) return 0d;
|
||||
double pay = kg * GameDefs.PerKg(kind) * PayoutMul;
|
||||
Money.Value += pay;
|
||||
Shipped.Value += kg;
|
||||
DepositedRpc(at, pay, kg);
|
||||
return pay;
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void DepositRpc(float kg, byte kind, Vector3 at, RpcParams rpc = default)
|
||||
{
|
||||
if (kind > (byte)CargoKind.Brick) return;
|
||||
ServerDeposit(Mathf.Clamp(kg, 0f, 50000f), (CargoKind)kind, at);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void DepositedRpc(Vector3 at, double pay, double kg) => Deposited?.Invoke(at, pay, kg);
|
||||
|
||||
/// <summary>Tie grass from a tool into a bundle at this spot.</summary>
|
||||
[Rpc(SendTo.Server)]
|
||||
public void BundleRpc(float kg, Vector3 at, Vector3 velocity, RpcParams rpc = default)
|
||||
{
|
||||
if (Spawner.Instance) Spawner.Instance.SpawnCargo(CargoKind.Grass, at, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f), velocity, Mathf.Clamp(kg, 0.01f, GameDefs.BundleKg));
|
||||
}
|
||||
|
||||
// ───────────────────────── matrix ─────────────────────────
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void BuyPerkRpc(int perk, RpcParams rpc = default)
|
||||
{
|
||||
if (perk < 0 || perk >= (int)PerkId.Count) return;
|
||||
var def = GameDefs.Perk((PerkId)perk);
|
||||
int lvl = Level(def.id);
|
||||
if (lvl >= def.maxLevel || !PerkAvailable(def) || Money.Value < def.PriceFor(lvl)) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
||||
Money.Value -= def.PriceFor(lvl);
|
||||
Perks[perk] = (byte)(lvl + 1);
|
||||
PurchasedRpc(PlayerName(rpc.Receive.SenderClientId), def.maxLevel > 1 ? Loc.Key(def.nameEn, GameDefs.ToRoman(lvl + 1)) : Loc.Key(def.nameEn));
|
||||
Save();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams)]
|
||||
public void DeniedRpc(RpcParams p = default) { Sfx.Play("error"); }
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void PurchasedRpc(FixedString64Bytes who, FixedString64Bytes what) => Purchased?.Invoke(who.ToString(), what.ToString());
|
||||
|
||||
public string PlayerName(ulong client)
|
||||
{
|
||||
var p = PlayerOf(client);
|
||||
return p ? p.DisplayName : Loc.N("Someone");
|
||||
}
|
||||
|
||||
public static PlayerAgent PlayerOf(ulong client)
|
||||
{
|
||||
foreach (var p in PlayerAgent.All) if (p.OwnerClientId == client) return p;
|
||||
return null;
|
||||
}
|
||||
|
||||
// ───────────────────────── supply wall (personal) ─────────────────────────
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void BuyToolRpc(byte tool, RpcParams rpc = default)
|
||||
{
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || tool >= GameDefs.ToolCount) return;
|
||||
var d = GameDefs.Tool((ToolId)tool);
|
||||
double price = ToolPrice(d);
|
||||
if (who.Owns((ToolId)tool) || Money.Value < price) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
||||
Money.Value -= price;
|
||||
who.Owned.Value |= (ushort)(1 << tool);
|
||||
SaveCrew(who);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void BuyBeltSlotRpc(RpcParams rpc = default)
|
||||
{
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who) return;
|
||||
long price = GameDefs.BeltSlotPrice(who.BeltSlots.Value);
|
||||
if (who.BeltSlots.Value >= GameDefs.MaxBeltSlots || Money.Value < price) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
||||
Money.Value -= price;
|
||||
who.BeltSlots.Value++;
|
||||
SaveCrew(who);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void BuyGearRpc(byte gear, RpcParams rpc = default)
|
||||
{
|
||||
var who = PlayerOf(rpc.Receive.SenderClientId);
|
||||
if (!who || gear < (byte)GearId.Jetpack || gear > (byte)GearId.NightVision) return;
|
||||
long price = GameDefs.GearPrice((GearId)gear);
|
||||
if (who.HasGear((GearId)gear) || Money.Value < price) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
||||
Money.Value -= price;
|
||||
who.Owned.Value |= (ushort)(1 << gear);
|
||||
SaveCrew(who);
|
||||
}
|
||||
|
||||
/// <summary>Server: someone joined: give them back their tools, or nothing at all on the first day.</summary>
|
||||
public void ServerRestoreCrew(PlayerAgent p)
|
||||
{
|
||||
foreach (var c in _crew)
|
||||
if (c.key == p.SaveId)
|
||||
{
|
||||
p.Owned.Value = (ushort)c.owned;
|
||||
p.BeltSlots.Value = (byte)Mathf.Clamp(c.slots, 1, GameDefs.MaxBeltSlots);
|
||||
if (c.owned != 0 && c.belt != null && c.bins != null) p.RestoreToolsRpc(c.owned, c.bins, c.belt, c.current);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
CrewSave CrewOf(PlayerAgent p)
|
||||
{
|
||||
var c = _crew.Find(x => x.key == p.SaveId);
|
||||
if (c == null) { c = new CrewSave { key = p.SaveId }; _crew.Add(c); }
|
||||
c.owned = p.Owned.Value;
|
||||
c.slots = p.BeltSlots.Value;
|
||||
return c;
|
||||
}
|
||||
|
||||
void SaveCrew(PlayerAgent p)
|
||||
{
|
||||
CrewOf(p);
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>Server: what this player's tools hold, for the next save.</summary>
|
||||
public void ServerStoreTools(PlayerAgent p, float[] bins, int[] belt, int current)
|
||||
{
|
||||
if (!p.ClaimedSave) return;
|
||||
var c = CrewOf(p);
|
||||
c.bins = bins;
|
||||
c.belt = belt;
|
||||
c.current = current;
|
||||
}
|
||||
|
||||
// ───────────────────────── tick ─────────────────────────
|
||||
|
||||
float _saveTimer, _backupAt = 60f;
|
||||
|
||||
float _powerTimer;
|
||||
|
||||
public void ServerSetPhase(float phase) => DayOffset.Value = Sun.OffsetFor(phase);
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!IsServer || !IsSpawned) return;
|
||||
TickSectors();
|
||||
TickWeather();
|
||||
_powerTimer += Time.deltaTime;
|
||||
if (_powerTimer > 0.25f) { PowerGrid.Tick(_powerTimer); _powerTimer = 0f; }
|
||||
_saveTimer += Time.deltaTime;
|
||||
if (_saveTimer > 30f) { _saveTimer = 0f; Save(); }
|
||||
if (Time.time > _backupAt)
|
||||
{
|
||||
_backupAt = Time.time + 1800f;
|
||||
Save();
|
||||
SaveSlots.Backup();
|
||||
}
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
public void AnnounceRpc(FixedString128Bytes text) => Announcement?.Invoke(text.ToString());
|
||||
|
||||
// ───────────────────────── persistence (host) ─────────────────────────
|
||||
|
||||
public void Save()
|
||||
{
|
||||
if (!IsServer) return;
|
||||
var d = new SaveData { ver = 6, level = Size.Value, money = Money.Value, shipped = Shipped.Value, mown = Mown.Value, crew = _crew, day = Sun.Phase, vehicles = PackVehicles(), banned = _banned };
|
||||
d.perks = new int[Perks.Count];
|
||||
for (int i = 0; i < Perks.Count; i++) d.perks[i] = Perks[i];
|
||||
d.tiles = new int[Tiles.Count];
|
||||
for (int i = 0; i < Tiles.Count; i++) d.tiles[i] = Tiles[i];
|
||||
d.found = new int[Found.Count];
|
||||
for (int i = 0; i < Found.Count; i++) d.found[i] = Found[i];
|
||||
d.stations = new int[Opened.Count];
|
||||
for (int i = 0; i < Opened.Count; i++) d.stations[i] = Opened[i];
|
||||
foreach (var p in BuildPiece.All)
|
||||
if (p && p.IsSpawned) d.pieces.Add(new PieceSave { id = (int)p.piece, at = p.transform.position, turn = p.transform.rotation, to = p.To.Value, cfg = p.Setting, free = p.Free.Value, state = p.GetComponent<IPieceState>()?.State });
|
||||
foreach (var c in Cargo.All)
|
||||
if (c && c.IsSpawned && !c.Grab.Consumed && d.cargo.Count < MaxSavedBundles)
|
||||
d.cargo.Add(new CargoSave { kind = (int)c.kind, kg = c.Kg.Value, at = c.transform.position });
|
||||
SaveSlots.Write(JsonUtility.ToJson(d), MowMap.Serialize());
|
||||
}
|
||||
|
||||
void Load()
|
||||
{
|
||||
var json = SaveSlots.Read();
|
||||
SaveData d = null;
|
||||
if (!string.IsNullOrEmpty(json))
|
||||
{
|
||||
try { d = JsonUtility.FromJson<SaveData>(json); }
|
||||
catch (Exception e) { Debug.LogWarning("[Save] corrupt save, starting fresh: " + e.Message); }
|
||||
}
|
||||
bool fresh = d == null || d.tiles == null || d.tiles.Length == 0;
|
||||
if (d == null) d = new SaveData();
|
||||
// the ball first: the mow map, the stakes and every piece go down on it
|
||||
var level = fresh ? Difficulties.Chosen : (Difficulty)d.level;
|
||||
if (fresh && CommandLine.Get("-difficulty") is string forced && byte.TryParse(forced, out byte f)) level = (Difficulty)f;
|
||||
Difficulties.Apply(level);
|
||||
Size.Value = (byte)Difficulties.Current;
|
||||
MowMap.Reset();
|
||||
if (!fresh) LoadMow();
|
||||
Money.Value = d.money;
|
||||
Shipped.Value = d.shipped;
|
||||
ServerSetPhase(d.day);
|
||||
Mown.Value = MowMap.MownArea();
|
||||
MowMap.Count();
|
||||
Closed.Value = MowMap.Finished;
|
||||
if (d.found != null) foreach (int id in d.found) Found.Add(id);
|
||||
if (d.stations != null) foreach (int id in d.stations) Opened.Add((byte)id);
|
||||
_banned = d.banned ?? new List<string>();
|
||||
_crew = d.crew ?? new List<CrewSave>();
|
||||
if (d.perks != null) for (int i = 0; i < d.perks.Length && i < Perks.Count; i++) Perks[i] = (byte)d.perks[i];
|
||||
// machines used to be crew upgrades after the last perk: what was paid for them comes back
|
||||
if (d.perks != null && d.ver < 2)
|
||||
for (int i = Perks.Count; i < d.perks.Length && i - Perks.Count < OldFleet.Length; i++)
|
||||
for (int l = 0; l < d.perks[i] && l < OldFleet[i - Perks.Count].Length; l++) Money.Value += OldFleet[i - Perks.Count][l];
|
||||
if (fresh)
|
||||
{
|
||||
for (int x = -1; x <= 1; x++) for (int z = -1; z <= 1; z++) Tiles.Add(PackTile(x, z));
|
||||
TilesChanged?.Invoke();
|
||||
Spawner.Instance?.ServerSpawnStarter();
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var t in d.tiles) Tiles.Add(t);
|
||||
TilesChanged?.Invoke();
|
||||
if (d.ver < 1)
|
||||
{
|
||||
// what stood on the old grid can't be placed any more: the crew gets its money back
|
||||
if (d.pieces != null) foreach (var p in d.pieces) if (!p.free) Money.Value += p.id == 4 ? 5d : 0.5d;
|
||||
Spawner.Instance?.ServerSpawnStarter();
|
||||
}
|
||||
else if (d.pieces != null)
|
||||
foreach (var p in d.pieces)
|
||||
if (p.id >= 0 && p.id < GameDefs.Pieces.Length) ServerSpawnPiece((PieceId)p.id, p.at, p.turn, p.to, p.cfg, p.free, p.state);
|
||||
// bundles lie where they were left; those on a belt climb back on by themselves
|
||||
if (d.cargo != null && Spawner.Instance)
|
||||
foreach (var c in d.cargo)
|
||||
if (c.kind >= 0 && c.kind <= (int)CargoKind.Brick && c.kg > 0f) Spawner.Instance.SpawnCargo((CargoKind)c.kind, c.at, Quaternion.identity, Vector3.zero, c.kg);
|
||||
}
|
||||
if (d.ver < 3) ServerSpawnStations();
|
||||
if (d.ver < 4) ServerSpawnIntakes();
|
||||
else if (d.ver < 5) ServerSwapIntakes();
|
||||
else if (d.ver < 6) ServerRespawnIntakes();
|
||||
if (!fresh) UnpackVehicles(d.vehicles);
|
||||
foreach (var p in PlayerAgent.All) if (p.ClaimedSave) ServerRestoreCrew(p);
|
||||
}
|
||||
|
||||
/// <summary>The slot's own map, or the newest backup that can still be read.</summary>
|
||||
static void LoadMow()
|
||||
{
|
||||
if (MowMap.LoadFile(SaveSlots.MapPath)) return;
|
||||
foreach (var path in SaveSlots.OlderMaps())
|
||||
{
|
||||
MowMap.Reset();
|
||||
if (MowMap.LoadFile(path)) return;
|
||||
}
|
||||
MowMap.Reset();
|
||||
}
|
||||
|
||||
public static void DeleteSave() => SaveSlots.Delete(SaveSlots.Current);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/TeamState.cs.meta
Normal file
2
Assets/Scripts/Gameplay/TeamState.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d2fd39d96b9c4fd4a8e102731453a26b
|
||||
45
Assets/Scripts/Gameplay/Treats.cs
Normal file
45
Assets/Scripts/Gameplay/Treats.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public enum TreatId : byte { Beer = 0, Cigar = 1 }
|
||||
|
||||
/// <summary>
|
||||
/// What the two vending machines on the deck sell for a kilo of grass, and the boost each one gives the one who had it.
|
||||
/// Personal and kept on this machine only: everyone buys their own, and a boost is gone when the match ends.
|
||||
/// </summary>
|
||||
public static class Treats
|
||||
{
|
||||
public const float CostKg = 1f;
|
||||
public const float Seconds = 150f;
|
||||
/// <summary>Grass Beer: the blade cuts this much wider.</summary>
|
||||
public const float BeerMow = 1.4f;
|
||||
/// <summary>Herb Cigar: you walk and run this much faster.</summary>
|
||||
public const float CigarMove = 1.3f;
|
||||
|
||||
static float _beerUntil = -1f, _cigarUntil = -1f;
|
||||
|
||||
public static event Action<TreatId> Started;
|
||||
|
||||
public static float Left(TreatId t) => Mathf.Max(0f, (t == TreatId.Beer ? _beerUntil : _cigarUntil) - Time.time);
|
||||
public static bool On(TreatId t) => Left(t) > 0f;
|
||||
public static float MowMul => On(TreatId.Beer) ? BeerMow : 1f;
|
||||
public static float MoveMul => On(TreatId.Cigar) ? CigarMove : 1f;
|
||||
|
||||
public static string Name(TreatId t) => t == TreatId.Beer ? Loc.T("Grass Beer") : Loc.T("Herb Cigar");
|
||||
public static string Boost(TreatId t) => t == TreatId.Beer ? Loc.T("Liquid Courage") : Loc.T("Second Wind");
|
||||
public static string Effect(TreatId t) => t == TreatId.Beer ? Loc.T("+40% cutting width") : Loc.T("+30% walking speed");
|
||||
public static string Icon(TreatId t) => t == TreatId.Beer ? "icon_treat_beer" : "icon_treat_cigar";
|
||||
|
||||
/// <summary>The boost starts (or starts over: a second can doesn't stack, it tops the clock back up).</summary>
|
||||
public static void Begin(TreatId t)
|
||||
{
|
||||
if (t == TreatId.Beer) _beerUntil = Time.time + Seconds;
|
||||
else _cigarUntil = Time.time + Seconds;
|
||||
Started?.Invoke(t);
|
||||
}
|
||||
|
||||
public static void Clear() { _beerUntil = _cigarUntil = -1f; }
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Treats.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Treats.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 342b966af039c1642bdeb249c62a582b
|
||||
36
Assets/Scripts/Gameplay/UnloadBay.cs
Normal file
36
Assets/Scripts/Gameplay/UnloadBay.cs
Normal file
@ -0,0 +1,36 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A drive-over grate with a bin behind it: a mower that rolls onto the grate empties its hopper into the bin, and two hatches
|
||||
/// at the back send it out as bundles onto belts. The cheap way to put a field's mowing straight onto a production line.
|
||||
/// The model is 7 m long; the prefab sets it so the grate is the front half and the hatches face back.
|
||||
/// </summary>
|
||||
public class UnloadBay : SiloPiece
|
||||
{
|
||||
const float GrateFront = 3.5f, GrateBack = -0.5f, GrateWide = 2.1f, HatchBack = 3.5f;
|
||||
|
||||
public override string Prompt => Loc.F("Unload Bay: drive a mower onto the grate (bin {0})", GameDefs.Kilos(Silo.Value));
|
||||
public override bool CanInteract => false;
|
||||
public override void Interact() { }
|
||||
public override string PadName => Loc.T("Unload Bay");
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
var back = -transform.forward;
|
||||
var at = transform.position + transform.up * GameDefs.BeltLowest + back * HatchBack;
|
||||
into.Add(new Port { at = at - transform.right * 0.8f, dir = back });
|
||||
into.Add(new Port { at = at + transform.right * 0.8f, dir = back });
|
||||
}
|
||||
|
||||
public override Vector3 PadSpot => transform.position + transform.forward * ((GrateFront + GrateBack) * 0.5f) + transform.up * 0.3f;
|
||||
|
||||
public override bool OnPad(Vector3 p)
|
||||
{
|
||||
var l = transform.InverseTransformPoint(p);
|
||||
return Mathf.Abs(l.x) < GrateWide + 0.6f && l.z > GrateBack - 1f && l.z < GrateFront + 1.2f && Mathf.Abs(l.y) < 3f;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/UnloadBay.cs.meta
Normal file
2
Assets/Scripts/Gameplay/UnloadBay.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ddfb4ed1297b00f4b9927da982bef6a3
|
||||
673
Assets/Scripts/Gameplay/Vehicle.cs
Normal file
673
Assets/Scripts/Gameplay/Vehicle.cs
Normal file
@ -0,0 +1,673 @@
|
||||
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 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 : 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;
|
||||
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 && 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) return;
|
||||
bool driving = LocalDriving;
|
||||
var input = driving ? Ctl.Move : Vector2.zero;
|
||||
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);
|
||||
|
||||
// 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 (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 && 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)
|
||||
{
|
||||
mowing = true;
|
||||
float kg = MowMap.Cut(_hasCut ? _lastCut : ip, ip, CutWidth) * GameDefs.GrassDensity;
|
||||
Tank.Value = Mathf.Min(Capacity, Tank.Value + kg);
|
||||
if (Tank.Value >= Capacity - 0.01f) { 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) 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);
|
||||
_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Vehicle.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Vehicle.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 17ec0b938d14a274590ecc1906e91725
|
||||
94
Assets/Scripts/Gameplay/VehicleShed.cs
Normal file
94
Assets/Scripts/Gameplay/VehicleShed.cs
Normal file
@ -0,0 +1,94 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A building machines come out of: the shed at the base and every garage the crew builds. A bought or called machine waits
|
||||
/// inside, the door tilts up and it drives out onto the pad in front (<see cref="Vehicle.ServerRollOut"/>), then the
|
||||
/// door comes down again. The door is purely for show and is opened on every machine by <see cref="TeamState.ShedDoorRpc"/>.
|
||||
/// </summary>
|
||||
public class VehicleShed : MonoBehaviour
|
||||
{
|
||||
/// <summary>The shed at the base, if the scene has one.</summary>
|
||||
public static VehicleShed Base;
|
||||
|
||||
/// <summary>The door, pivot on its top edge: it tilts up and in, under the roof, like a farm garage's up-and-over door.</summary>
|
||||
public Transform door;
|
||||
/// <summary>Where a machine waits inside and where it stops outside, in the shed's own space; out is along +Z.</summary>
|
||||
public Vector3 inside = new Vector3(0f, 0.6f, 0f), outside = new Vector3(0f, 0.6f, 7f);
|
||||
public bool isBase;
|
||||
/// <summary>Its size in its own space: half the width, the inside of the back wall, the door line, the eaves.</summary>
|
||||
public float halfWide = 8f, backWall = -1.9f, doorLine = 2.3f, eaves = 2.5f;
|
||||
|
||||
public static readonly System.Collections.Generic.List<VehicleShed> All = new System.Collections.Generic.List<VehicleShed>();
|
||||
void OnEnable() => All.Add(this);
|
||||
void OnDisable() => All.Remove(this);
|
||||
|
||||
/// <summary>The shed this spot is inside or on the pad in front of.</summary>
|
||||
public static VehicleShed Near(Vector3 p)
|
||||
{
|
||||
foreach (var s in All)
|
||||
{
|
||||
if (!s) continue;
|
||||
var l = s.transform.InverseTransformPoint(p);
|
||||
if (Mathf.Abs(l.x) < s.halfWide && l.z > s.backWall && l.z < s.doorLine + 11f && Mathf.Abs(l.y) < 4f) return s;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public const float DoorUp = 1.1f, Wait = 0.9f, Drive = 3.2f, Hold = 1.6f;
|
||||
|
||||
Quaternion _doorRest;
|
||||
const float DoorTilt = 86f;
|
||||
float _open, _openUntil = -1f;
|
||||
|
||||
public Vector3 Inside => transform.TransformPoint(inside);
|
||||
public Vector3 Outside => transform.TransformPoint(outside);
|
||||
|
||||
/// <summary>
|
||||
/// Where a machine whose tail reaches <paramref name="back"/> metres behind its middle waits: as deep inside as it fits.
|
||||
/// One taller than the eaves would stick up through the roof, so it waits with its tail just inside the door instead.
|
||||
/// </summary>
|
||||
public Vector3 InsideFor(float back, float top)
|
||||
{
|
||||
float z = top > eaves ? doorLine - 0.6f + back : Mathf.Min(backWall + 0.4f + back, doorLine + 1.5f);
|
||||
return transform.TransformPoint(new Vector3(inside.x, inside.y, z));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>Where it stops outside: far enough out that its tail clears the door.</summary>
|
||||
public Vector3 OutsideFor(float back) => transform.TransformPoint(new Vector3(outside.x, outside.y, Mathf.Max(outside.z, doorLine + 0.8f + back)));
|
||||
public Quaternion Facing => Quaternion.LookRotation(transform.forward, transform.up);
|
||||
|
||||
void Awake()
|
||||
{
|
||||
if (isBase) Base = this;
|
||||
if (door) _doorRest = Quaternion.Inverse(transform.rotation) * door.rotation;
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
if (Base == this) Base = null;
|
||||
}
|
||||
|
||||
/// <summary>Raise the door for as long as a machine needs to get out.</summary>
|
||||
public void Open()
|
||||
{
|
||||
if (_open < 0.05f && door) Sfx.PlayAt("gate_shutter", door.position, 0.7f);
|
||||
_openUntil = Time.time + Wait + Drive + Hold;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!door) return;
|
||||
float want = Time.time < _openUntil ? 1f : 0f;
|
||||
if (Mathf.Approximately(_open, want)) return;
|
||||
if (want < 0.5f && _open >= 1f) Sfx.PlayAt("gate_shutter", door.position, 0.5f, 0.85f);
|
||||
_open = Mathf.MoveTowards(_open, want, Time.deltaTime / DoorUp);
|
||||
float e = _open * _open * (3f - 2f * _open);
|
||||
// about the shed's own X axis: the bottom edge swings in (toward -Z) and up
|
||||
door.rotation = transform.rotation * Quaternion.AngleAxis(DoorTilt * e, Vector3.right) * _doorRest;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/VehicleShed.cs.meta
Normal file
2
Assets/Scripts/Gameplay/VehicleShed.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e12b5ced579ab574d9da49856c59724c
|
||||
270
Assets/Scripts/Gameplay/VendingMachine.cs
Normal file
270
Assets/Scripts/Gameplay/VendingMachine.cs
Normal file
@ -0,0 +1,270 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The two machines on the deck that take a kilo of grass out of your tool and give you something for it: the green
|
||||
/// one a can of Grass Beer, the wooden one a Herb Cigar. Everything about it is a show: the grass slurps into the
|
||||
/// hopper, the sign flares, the machine shudders, the can thumps into the tray (or a knob pulls and the drawer slides
|
||||
/// out with a ding), and the thing flies up into your hand. The others see the same show at their end.
|
||||
/// </summary>
|
||||
public class VendingMachine : MonoBehaviour, IInteractable
|
||||
{
|
||||
public TreatId kind;
|
||||
public Renderer sign, display;
|
||||
public Transform body, button, tray, drawer, hopper, dropPoint;
|
||||
public Transform[] knobs;
|
||||
|
||||
public static readonly List<VendingMachine> All = new List<VendingMachine>();
|
||||
|
||||
bool _busy;
|
||||
float _flash, _deny, _shudder;
|
||||
MaterialPropertyBlock _mpb;
|
||||
Color _signBase, _displayBase;
|
||||
Vector3 _buttonRest, _drawerRest, _bodyScale, _hopperScale = Vector3.one;
|
||||
Quaternion _trayRest;
|
||||
Vector3[] _knobRest;
|
||||
static readonly int EmissionId = Shader.PropertyToID("_EmissionColor");
|
||||
|
||||
static readonly Color BeerGlow = new Color(1f, 0.82f, 0.32f), CigarGlow = new Color(1f, 0.55f, 0.22f), Deny = new Color(1f, 0.15f, 0.1f);
|
||||
|
||||
public string Prompt => Loc.F("{0}: 1 kg of grass from your tool. {1}, {2} for 2½ minutes", Treats.Name(kind), Treats.Boost(kind), Treats.Effect(kind));
|
||||
public bool CanInteract => TeamState.Instance && !_busy && !TreatHand.Busy;
|
||||
|
||||
void OnEnable() => All.Add(this);
|
||||
void OnDisable() => All.Remove(this);
|
||||
|
||||
void Start()
|
||||
{
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
_signBase = kind == TreatId.Beer ? new Color(0.25f, 1f, 0.5f) : CigarGlow;
|
||||
_displayBase = kind == TreatId.Beer ? new Color(0.45f, 1f, 0.55f) : new Color(1f, 0.72f, 0.4f);
|
||||
if (button) _buttonRest = button.localPosition;
|
||||
if (drawer) _drawerRest = drawer.localPosition;
|
||||
if (tray) _trayRest = tray.localRotation;
|
||||
if (body) _bodyScale = body.localScale;
|
||||
if (hopper) _hopperScale = hopper.localScale;
|
||||
if (knobs != null)
|
||||
{
|
||||
_knobRest = new Vector3[knobs.Length];
|
||||
for (int i = 0; i < knobs.Length; i++) if (knobs[i]) _knobRest[i] = knobs[i].localPosition;
|
||||
}
|
||||
}
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
var me = PlayerAgent.Local;
|
||||
if (!me || _busy) return;
|
||||
if (me.Tools.Carried < Treats.CostKg - 0.001f)
|
||||
{
|
||||
_deny = 1f;
|
||||
Sfx.PlayAt("error", transform.position, 0.7f);
|
||||
Hud.Toast(Loc.T("Bring 1 kg of grass in your tool: mow a little first"), Hud.ToastKind.Warn);
|
||||
return;
|
||||
}
|
||||
var from = me.Tools.Nozzle;
|
||||
me.Tools.Spend(Treats.CostKg);
|
||||
me.TreatRpc((byte)kind, transform.position, from);
|
||||
Play(true, from);
|
||||
}
|
||||
|
||||
/// <summary>Run the machine's show: for the buyer it ends with the treat in their hand, for everyone else it's just the show.</summary>
|
||||
public void Play(bool mine, Vector3 from)
|
||||
{
|
||||
if (_busy) return;
|
||||
StartCoroutine(Vend(mine, from));
|
||||
}
|
||||
|
||||
public static VendingMachine Nearest(Vector3 at)
|
||||
{
|
||||
VendingMachine best = null;
|
||||
float bd = 25f;
|
||||
foreach (var m in All)
|
||||
{
|
||||
float d = Vector3.Distance(m.transform.position, at);
|
||||
if (d < bd) { bd = d; best = m; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
Vector3 Out => transform.forward;
|
||||
Vector3 Up => transform.up;
|
||||
Vector3 Drop => dropPoint ? dropPoint.position : transform.position + Out * 0.35f + Up * 0.25f;
|
||||
Vector3 Mouth => hopper ? hopper.position : transform.position + Out * 0.45f + Up * 1.4f;
|
||||
|
||||
IEnumerator Vend(bool mine, Vector3 from)
|
||||
{
|
||||
_busy = true;
|
||||
bool beer = kind == TreatId.Beer;
|
||||
|
||||
// the grass goes in: a green stream from the tool to the hopper, and the hopper gulps it
|
||||
Sfx.PlayAt("vend_hopper", Mouth, 0.9f);
|
||||
for (float t = 0f; t < 0.45f; t += Time.deltaTime)
|
||||
{
|
||||
Fx.Stream(from, Mouth, 1f);
|
||||
if (hopper) hopper.localScale = _hopperScale * (1f + Mathf.Sin(t * 30f) * 0.06f);
|
||||
yield return null;
|
||||
}
|
||||
if (hopper) { hopper.localScale = _hopperScale; Tween.Punch(hopper, 0.25f, 0.35f); }
|
||||
Fx.Sparkles(Mouth, 14, new Color(0.55f, 0.9f, 0.3f));
|
||||
|
||||
// pressed: the button goes in, the sign flares
|
||||
_flash = 1f;
|
||||
if (button) StartCoroutine(Press(button, _buttonRest, -0.03f, 0.18f));
|
||||
if (!beer && knobs != null && knobs.Length > 0)
|
||||
{
|
||||
int k = Random.Range(0, knobs.Length);
|
||||
if (knobs[k]) StartCoroutine(Press(knobs[k], _knobRest[k], 0.07f, 0.45f));
|
||||
Sfx.PlayAt("knob_pull", transform.position + Up * 1f, 0.9f);
|
||||
}
|
||||
yield return new WaitForSeconds(0.2f);
|
||||
|
||||
Transform item;
|
||||
if (beer)
|
||||
{
|
||||
// the machine thinks about it: a whirr and a shudder, then the can falls into the tray
|
||||
Sfx.PlayAt("vend_whirr", transform.position + Up, 0.9f);
|
||||
_shudder = 1f;
|
||||
yield return new WaitForSeconds(0.75f);
|
||||
item = Spawn("SM_BeerCan", Drop + Up * 0.45f, Quaternion.LookRotation(Out, Up) * Quaternion.Euler(90f, 0f, 0f));
|
||||
for (float t = 0f; t < 0.2f; t += Time.deltaTime)
|
||||
{
|
||||
if (item) item.position = Vector3.Lerp(Drop + Up * 0.45f, Drop, t * t / 0.04f);
|
||||
yield return null;
|
||||
}
|
||||
if (item) { item.position = Drop; Tween.Punch(item, 0.3f, 0.3f); }
|
||||
if (tray) StartCoroutine(Flap(tray, _trayRest));
|
||||
Fx.Steam(Drop + Up * 0.1f, 0.25f);
|
||||
Fx.Sparkles(Drop + Up * 0.1f, 18, new Color(1f, 0.85f, 0.35f));
|
||||
if (mine) CameraFx.Shake(0.03f);
|
||||
}
|
||||
else
|
||||
{
|
||||
// the drawer slides out with a ding, a wisp of smoke, and there's your cigar
|
||||
Sfx.PlayAt("drawer_bell", transform.position + Up * 0.8f, 0.9f);
|
||||
if (drawer) StartCoroutine(Slide(drawer, _drawerRest, 0.2f, 0.3f));
|
||||
yield return new WaitForSeconds(0.32f);
|
||||
item = Spawn("SM_Cigar", Drop, Quaternion.LookRotation(transform.right, Up));
|
||||
if (item) Tween.Punch(item, 0.3f, 0.35f);
|
||||
Fx.Smoke(Drop + Up * 0.2f, 0.25f);
|
||||
Fx.Sparkles(Drop + Up * 0.1f, 18, new Color(1f, 0.6f, 0.25f));
|
||||
}
|
||||
yield return new WaitForSeconds(0.35f);
|
||||
|
||||
// it flies up into your hand (or just pops away for the people watching)
|
||||
var cam = CameraFx.Cam;
|
||||
if (item && mine && cam)
|
||||
{
|
||||
var start = item.position;
|
||||
var spin = Random.rotation;
|
||||
for (float t = 0f; t < 0.32f; t += Time.deltaTime)
|
||||
{
|
||||
float k = Easing.Apply(Ease.InQuad, t / 0.32f);
|
||||
var to = cam.transform.position + cam.transform.forward * 0.35f - cam.transform.up * 0.15f;
|
||||
item.position = Vector3.Lerp(start, to, k) + Up * Mathf.Sin(k * Mathf.PI) * 0.6f;
|
||||
item.rotation = Quaternion.Slerp(item.rotation, spin, Time.deltaTime * 8f);
|
||||
yield return null;
|
||||
}
|
||||
Destroy(item.gameObject);
|
||||
TreatHand.I?.Play(kind);
|
||||
}
|
||||
else if (item)
|
||||
{
|
||||
Fx.Sparkles(item.position, 10, Color.white);
|
||||
Destroy(item.gameObject, 0.05f);
|
||||
}
|
||||
if (!beer && drawer) StartCoroutine(Slide(drawer, _drawerRest, 0f, 0.25f, 0.2f));
|
||||
yield return new WaitForSeconds(0.3f);
|
||||
_busy = false;
|
||||
}
|
||||
|
||||
Transform Spawn(string model, Vector3 at, Quaternion rot)
|
||||
{
|
||||
var src = AssetBank.I ? AssetBank.I.Model(model) : null;
|
||||
GameObject go;
|
||||
if (src) go = Instantiate(src, at, rot * src.transform.localRotation);
|
||||
else
|
||||
{
|
||||
go = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
|
||||
go.transform.SetPositionAndRotation(at, rot);
|
||||
go.transform.localScale = model == "SM_Cigar" ? new Vector3(0.025f, 0.07f, 0.025f) : new Vector3(0.066f, 0.06f, 0.066f);
|
||||
}
|
||||
foreach (var c in go.GetComponentsInChildren<Collider>()) Destroy(c);
|
||||
return go.transform;
|
||||
}
|
||||
|
||||
IEnumerator Press(Transform t, Vector3 rest, float depth, float hold)
|
||||
{
|
||||
var dir = t.parent ? t.parent.InverseTransformDirection(Out) : Out;
|
||||
for (float k = 0f; k < 1f; k += Time.deltaTime / 0.08f) { t.localPosition = rest + dir * depth * k; yield return null; }
|
||||
yield return new WaitForSeconds(hold);
|
||||
for (float k = 1f; k > 0f; k -= Time.deltaTime / 0.25f) { t.localPosition = rest + dir * depth * Easing.Apply(Ease.OutBack, k); yield return null; }
|
||||
t.localPosition = rest;
|
||||
}
|
||||
|
||||
IEnumerator Slide(Transform t, Vector3 rest, float to, float time, float delay = 0f)
|
||||
{
|
||||
if (delay > 0f) yield return new WaitForSeconds(delay);
|
||||
var dir = t.parent ? t.parent.InverseTransformDirection(Out) : Out;
|
||||
var from = t.localPosition;
|
||||
for (float k = 0f; k < 1f; k += Time.deltaTime / time)
|
||||
{
|
||||
t.localPosition = Vector3.LerpUnclamped(from, rest + dir * to, Easing.Apply(Ease.OutBack, k));
|
||||
yield return null;
|
||||
}
|
||||
t.localPosition = rest + dir * to;
|
||||
}
|
||||
|
||||
IEnumerator Flap(Transform t, Quaternion rest)
|
||||
{
|
||||
for (float k = 0f; k < 1f; k += Time.deltaTime / 0.5f)
|
||||
{
|
||||
float a = Mathf.Sin(k * Mathf.PI * 3f) * 28f * (1f - k);
|
||||
t.localRotation = rest * Quaternion.Euler(a, 0f, 0f);
|
||||
yield return null;
|
||||
}
|
||||
t.localRotation = rest;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
float dt = Time.deltaTime;
|
||||
_flash = Mathf.MoveTowards(_flash, 0f, dt * 1.4f);
|
||||
_deny = Mathf.MoveTowards(_deny, 0f, dt * 1.5f);
|
||||
_shudder = Mathf.MoveTowards(_shudder, 0f, dt * 1.3f);
|
||||
|
||||
// a neon sign: a slow breath, the odd flicker, and a flare when it's working
|
||||
float flicker = Random.value < dt * 0.6f ? 0.35f : 1f;
|
||||
float breath = 1.6f + 0.35f * Mathf.Sin(Time.time * 2.1f + transform.position.x);
|
||||
var glow = _signBase * (breath * flicker + _flash * 4f);
|
||||
if (_deny > 0f) glow = Color.Lerp(glow, Deny * 3f, Mathf.Abs(Mathf.Sin(_deny * 18f)));
|
||||
Paint(sign, glow);
|
||||
float blink = (Mathf.Repeat(Time.time * (_flash > 0f ? 6f : 1.2f), 1f) < 0.6f ? 1f : 0.4f) * (1.4f + _flash * 2f);
|
||||
Paint(display, _deny > 0f ? Deny * 2.5f : _displayBase * blink);
|
||||
|
||||
if (body)
|
||||
{
|
||||
float s = _shudder > 0f ? Mathf.Sin(Time.time * 55f) * 0.012f * _shudder : 0f;
|
||||
body.localScale = new Vector3(_bodyScale.x * (1f - s * 0.5f), _bodyScale.y * (1f + s), _bodyScale.z * (1f - s * 0.5f));
|
||||
}
|
||||
}
|
||||
|
||||
void Paint(Renderer r, Color c)
|
||||
{
|
||||
if (!r) return;
|
||||
// only the first slot glows: the beer sign's picture keeps its own colours
|
||||
if (r.sharedMaterials.Length > 1)
|
||||
{
|
||||
r.GetPropertyBlock(_mpb, 0);
|
||||
_mpb.SetColor(EmissionId, c);
|
||||
r.SetPropertyBlock(_mpb, 0);
|
||||
return;
|
||||
}
|
||||
r.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(EmissionId, c);
|
||||
r.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/VendingMachine.cs.meta
Normal file
2
Assets/Scripts/Gameplay/VendingMachine.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cb45ff9d6531592428a7b706b94183a0
|
||||
Reference in New Issue
Block a user