La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.
package vehicle
import "github.com/nsgo-dev/game/pkg/vehicle"Resumen
Package vehicle simulates raycast cars on a physics3d.World: wheel colliders cast from the chassis, spring-damper suspension, longitudinal and lateral tire friction inside a friction circle, and engine, brake, steering and handbrake input. It also tracks race checkpoints and laps on trigger bodies and records ghost replays of a lap as YAML.
Model
A Vehicle is one dynamic physics3d.Body (the chassis, whose Pos is the center of mass) plus a list of wheels. Every fixed step, Vehicle.Step casts one ray per wheel from its anchor along the chassis' down axis, turns the compression into a suspension force, and applies tire impulses at the contact point before World.Step integrates the chassis. Wheels have no bodies of their own, so they cannot snag on geometry and cost one raycast each.
Vehicles face -Z in local space, with +X to the right and +Y up, matching the conventions in the 3D models guide.
Files
A car's tuning is a Config, written by people as versioned YAML (ParseConfig and EncodeConfig). A lap's ghost is a Ghost, written by the game as versioned YAML (ParseGhost and EncodeGhost). Both refuse unknown fields, encode deterministically and round-trip without change.
Determinism
Vehicle.Step uses no maps, wall clock or randomness and visits wheels in Config order, so the same Config, start pose and per-step Input on the same World produce bit-identical poses, lap times and ghosts across runs. Feeding Input from a replay.Player (through Controls.Read) reproduces a recorded drive.
Índice
- Constantes
- func AddCheckpoint(world *physics3d.World, shape physics3d.Shape, pos physics3d.Vec3) *physics3d.Body
- func EncodeConfig(cfg Config) ([]byte, error)
- func EncodeGhost(g *Ghost) ([]byte, error)
- type Config
- type Controls
- type Ghost
- type GhostFrame
- type GhostRecorder
- type Input
- type LapEvent
- type Race
- type Racer
- type Snapshot
- type Vehicle
- func New(world *physics3d.World, cfg Config, pos physics3d.Vec3, rot physics3d.Quat) (*Vehicle, error)
- func (v *Vehicle) Checksum() uint64
- func (v *Vehicle) Config() Config
- func (v *Vehicle) Forward() physics3d.Vec3
- func (v *Vehicle) Grounded() int
- func (v *Vehicle) Input() Input
- func (v *Vehicle) Reset(pos physics3d.Vec3, rot physics3d.Quat)
- func (v *Vehicle) Restore(snap Snapshot, world *physics3d.World) error
- func (v *Vehicle) Save() Snapshot
- func (v *Vehicle) SetInput(in Input)
- func (v *Vehicle) Speed() float32
- func (v *Vehicle) Step(world *physics3d.World, dt time.Duration)
- func (v *Vehicle) Up() physics3d.Vec3
- func (v *Vehicle) WheelTransform(i int) (physics3d.Vec3, physics3d.Quat)
- type Wheel
- type WheelConfig
- type WheelSnapshot
Constantes
const ConfigVersion = 1ConfigVersion is the Config schema version written by EncodeConfig and accepted by ParseConfig.
const GhostVersion = 1GhostVersion is the Ghost schema version written by EncodeGhost and accepted by ParseGhost.
Funciones
func AddCheckpoint(world *physics3d.World, shape physics3d.Shape, pos physics3d.Vec3) *physics3d.BodyAddCheckpoint adds a static trigger body with shape at pos to world and returns it, ready to pass to NewRace.
func EncodeConfig(cfg Config) ([]byte, error)EncodeConfig validates cfg and serializes it as deterministic 2-space YAML that ParseConfig reads back unchanged.
func EncodeGhost(g *Ghost) ([]byte, error)EncodeGhost validates g and serializes it as deterministic 2-space YAML, each frame's position and rotation on a flow-style line of its own, that ParseGhost reads back unchanged.
Tipos
type Config struct {
// Version is the schema version; it must equal ConfigVersion.
Version int `yaml:"version"`
// Name optionally labels the car.
Name string `yaml:"name,omitempty"`
// Mass is the chassis mass in kilograms (> 0).
Mass float32 `yaml:"mass"`
// ChassisHalfExtents are the half sizes of the chassis collision box (each > 0).
ChassisHalfExtents [3]float32 `yaml:"chassisHalfExtents,flow"`
// ChassisOffset moves the chassis box relative to the center of mass; a positive Y lowers the center of mass inside the box, which steadies the car.
ChassisOffset [3]float32 `yaml:"chassisOffset,flow"`
// EngineForce is the total forward drive force at full throttle and standstill, split evenly over the drive wheels (>= 0).
EngineForce float32 `yaml:"engineForce"`
// ReverseForce is the total drive force at full reverse throttle (>= 0).
ReverseForce float32 `yaml:"reverseForce"`
// MaxSpeed is the forward speed in m/s at which the engine force fades to zero (> 0).
MaxSpeed float32 `yaml:"maxSpeed"`
// MaxReverseSpeed is the reverse speed in m/s at which the reverse force fades to zero (> 0).
MaxReverseSpeed float32 `yaml:"maxReverseSpeed"`
// BrakeForce is the total braking force at full brake, split evenly over the brake wheels (>= 0).
BrakeForce float32 `yaml:"brakeForce"`
// HandbrakeGrip scales the lateral grip of handbrake wheels while the handbrake is held, in [0, 1]; lower values slide more.
HandbrakeGrip float32 `yaml:"handbrakeGrip"`
// MaxSteerAngle is the largest steering angle of steered wheels in degrees, in [0, 80].
MaxSteerAngle float32 `yaml:"maxSteerAngle"`
// SteerRate is how fast steered wheels turn toward the requested angle, in degrees per second (> 0).
SteerRate float32 `yaml:"steerRate"`
// Drag is the aerodynamic drag coefficient: the drag force is Drag * speed² against the velocity (>= 0).
Drag float32 `yaml:"drag"`
// RollingResistance is the rolling resistance coefficient applied against each grounded wheel's rolling speed, as a fraction of its load (>= 0).
RollingResistance float32 `yaml:"rollingResistance"`
// RollInfluence scales how much lateral tire force rolls the chassis, in [0, 1]: 0 applies it at the center of mass' height, 1 at the contact point.
RollInfluence float32 `yaml:"rollInfluence"`
// AngularDamping damps the chassis' angular velocity (>= 0), as physics3d.Body.AngularDamping.
AngularDamping float32 `yaml:"angularDamping"`
// Wheels lists the wheels in a fixed order (1 to 32, unique names).
Wheels []WheelConfig `yaml:"wheels"`
}Config is a car's tuning: chassis mass and box, engine, brakes, steering, drag and wheels. Lengths are meters, masses kilograms, forces newtons and angles degrees.
Positions are in chassis space relative to the center of mass (the chassis body's Pos), with -Z forward, +X right and +Y up.
func ParseConfig(data []byte) (Config, error)ParseConfig decodes a YAML car Config and validates it. Unknown fields and trailing YAML documents are rejected.
func ReferenceConfig() ConfigReferenceConfig returns the tuning of the reference car: a 1200 kg rear-wheel-drive hatchback with four wheels, about 0.5 g of acceleration, 1 g of braking and a 40 m/s top speed.
func (cfg *Config) Validate() errorValidate checks that cfg uses ConfigVersion and that every value is finite and within the range its field documents.
type Controls struct {
// Throttle is the axis read into Input.Throttle, in [-1, 1].
Throttle string
// Brake is the axis read into Input.Brake, in [0, 1].
Brake string
// Steer is the axis read into Input.Steer, in [-1, 1] with positive steering right.
Steer string
// Handbrake is the action whose pressed state sets Input.Handbrake.
Handbrake string
}Controls names the input axes and action a car is driven with, so the same driving code reads live input (*input.Actions), a replay.Recorder while recording, or a replay.Player while playing a recording back.
func DefaultControls() ControlsDefaultControls returns Controls reading the axes "throttle", "brake" and "steer" and the action "handbrake".
func (c Controls) Actions() []stringActions returns the action names in c for replay.NewRecorder; an empty Handbrake name is left out.
func (c Controls) Axes() []stringAxes returns the axis names in c, in the order Throttle, Brake, Steer, for replay.NewRecorder; empty names are left out.
func (c Controls) Read(src replay.ActionSource) InputRead samples src into an Input, clamping each axis to its range and treating NaN as 0. An empty name reads as zero or released. Read does not call src.Step.
type Ghost struct {
// Version is the schema version; it must equal GhostVersion.
Version int `yaml:"version"`
// Name optionally labels the ghost, such as the racer or track.
Name string `yaml:"name,omitempty"`
// Rate is the fixed step rate the ghost was recorded at, in steps per second (> 0).
Rate int `yaml:"rate"`
// Interval is the number of steps between frames (>= 1).
Interval int `yaml:"interval"`
// LapSteps is the recorded lap's duration in steps, or 0 when unknown. When set, the last frame is at step LapSteps, so a lap whose length is not a multiple of Interval still ends on the finish line.
LapSteps int `yaml:"lapSteps,omitempty"`
// Frames holds the sampled poses; frame i is at step i * Interval, except that the last frame is at step LapSteps when LapSteps is set.
Frames []GhostFrame `yaml:"frames"`
}Ghost is a recorded lap: the chassis pose sampled every Interval steps, played back as a translucent rival. It is pose data, so playing it needs no physics and costs nothing per frame beyond drawing.
func ParseGhost(data []byte) (*Ghost, error)ParseGhost decodes a YAML Ghost and validates it. Unknown fields and trailing YAML documents are rejected.
func (g *Ghost) Pose(step float64) (physics3d.Vec3, physics3d.Quat)Pose returns the ghost's pose at step, which may be fractional to interpolate between fixed steps (pass the step plus game.Loop's draw alpha). Positions are interpolated linearly and orientations spherically; steps outside the recording clamp to its first or last frame. An empty ghost returns the origin and identity.
func (g *Ghost) Steps() intSteps returns the number of steps the ghost's frames span: LapSteps when it is set, otherwise (len(Frames) - 1) * Interval.
func (g *Ghost) Validate() errorValidate checks that g uses GhostVersion, has a positive rate and interval, at most an hour of frames at 60 Hz spanning at most math.MaxInt32 steps, a LapSteps that falls within the last Interval before the last frame when it is set, and finite poses with non-zero quaternions.
type GhostFrame struct {
// P is the position (x, y, z).
P [3]float32 `yaml:"p,flow"`
// R is the orientation quaternion (x, y, z, w).
R [4]float32 `yaml:"r,flow"`
}GhostFrame is one sampled chassis pose.
type GhostRecorder struct {
// Interval is the number of steps between frames; values < 1 record every step.
Interval int
// contains filtered or unexported fields
}GhostRecorder samples a body's pose every Interval steps into a Ghost.
func (r *GhostRecorder) Finish(pos physics3d.Vec3, rot physics3d.Quat)Finish samples pos and rot as the recording's last frame, even when the current step falls between Interval samples, then advances one step. Call it instead of Record on the step the lap ends, such as from Race.OnLap, and pass the lap's step count to Ghost, so the ghost ends exactly on the finish line.
func (r *GhostRecorder) Ghost(rate, lapSteps int) *GhostGhost returns a copy of the recorded frames as a Ghost at rate steps per second, with LapSteps set to lapSteps: the step of the last frame, which is Steps() - 1 after Finish, or 0 when unknown.
func (r *GhostRecorder) Record(pos physics3d.Vec3, rot physics3d.Quat)Record samples pos and rot if the current step falls on Interval, then advances one step. Call it once per fixed step, after World.Step, and once when the lap starts.
func (r *GhostRecorder) Reset()Reset discards the recorded frames, such as when a new lap starts.
func (r *GhostRecorder) Steps() intSteps returns how many steps were recorded since the last Reset.
type Input struct {
// Throttle in [-1, 1]: positive drives forward with EngineForce, negative drives backward with ReverseForce.
Throttle float32
// Brake in [0, 1] scales BrakeForce on brake wheels.
Brake float32
// Steer in [-1, 1]: positive steers right, negative left.
Steer float32
// Handbrake locks handbrake wheels and lowers their lateral grip to HandbrakeGrip.
Handbrake bool
}Input is one step's driver input.
type LapEvent struct {
// Racer is the racer that completed the lap.
Racer *Racer
// Lap is the 1-based number of the lap just completed.
Lap int
// Steps is the lap's duration in steps.
Steps int
// Best reports whether the lap is the racer's fastest so far.
Best bool
// Finished reports whether this was the racer's final lap.
Finished bool
}LapEvent reports a completed lap to Race.OnLap.
type Race struct {
// Checkpoints are the trigger bodies in track order; index 0 is the start/finish line.
Checkpoints []*physics3d.Body
// Laps is the number of laps that finishes the race.
Laps int
// OnLap, when set, is called for every completed lap, in the order Observe sees them.
OnLap func(LapEvent)
// contains filtered or unexported fields
}Race tracks racers through an ordered list of checkpoint triggers for a fixed number of laps.
Checkpoint 0 is the start/finish line. Racers start a lap on the step they are added and must enter checkpoints 1, 2, ... in order and then checkpoint 0 to complete it; entering any other checkpoint is ignored, so cutting the track does not count.
func NewRace(laps int, checkpoints ...*physics3d.Body) (*Race, error)NewRace returns a Race over checkpoints for laps laps. It needs at least two checkpoints, each a distinct trigger body, and at least one lap; a track that passes the same place twice, such as a figure eight's crossing, needs a trigger body for each pass.
func (r *Race) AddRacer(body *physics3d.Body, name string) *RacerAddRacer adds body as a racer whose first lap starts at the current step, heading for checkpoint 1.
func (r *Race) Observe(ev physics3d.ContactEvent)Observe handles a trigger event from World.OnTrigger, advancing a racer whose body entered its next checkpoint. Other events are ignored, so Observe can sit behind other trigger handlers.
func (r *Race) Racers() []*RacerRacers returns the racers in the order they were added.
func (r *Race) Standings() []*RacerStandings returns the racers from first to last: finished racers by finish step, then the rest by laps completed and checkpoints passed, with ties kept in the order racers were added.
func (r *Race) Step() intStep returns the current step: the number of Tick calls so far.
func (r *Race) Tick()Tick advances the race clock by one fixed step. Call it once per step, before World.Step, so a checkpoint entered during that World.Step is timed at the new step.
type Racer struct {
// Body is the racer's chassis, such as Vehicle.Body.
Body *physics3d.Body
// Name optionally labels the racer.
Name string
// Laps is the number of laps completed.
Laps int
// Next is the index of the checkpoint the racer must reach next; 0 is the start/finish line.
Next int
// LapStart is the step the current lap began on.
LapStart int
// LastLap is the duration of the last completed lap in steps, or 0 before the first.
LastLap int
// BestLap is the duration of the fastest completed lap in steps, or 0 before the first.
BestLap int
// Finished reports whether the racer completed every lap.
Finished bool
// FinishStep is the step the racer finished on, when Finished.
FinishStep int
// contains filtered or unexported fields
}Racer is one body's progress through a Race. Times are counted in fixed steps; multiply by the step duration for wall time.
type Snapshot struct {
Version int `json:"version"`
BodyID int `json:"bodyID"`
RayMask physics3d.LayerMask `json:"rayMask"`
Input Input `json:"input"`
Steer float32 `json:"steer"`
Wheels []WheelSnapshot `json:"wheels,omitempty"`
}Snapshot captures the complete deterministic runtime state of a Vehicle (steering, input, ray mask, and every wheel's suspension and spin state). Pair it with physics3d.World.Save/Restore to save and restore the full car simulation cleanly as JSON.
type Vehicle struct {
// Body is the chassis; its Pos is the center of mass.
Body *physics3d.Body
// Wheels holds each wheel's state, in Config.Wheels order.
Wheels []Wheel
// RayMask selects the layers wheel rays hit (0 hits every layer). Trigger bodies and the chassis itself are always skipped.
RayMask physics3d.LayerMask
// contains filtered or unexported fields
}Vehicle is a raycast car: a dynamic chassis body in a physics3d.World and the wheels that hold it up.
func New(world *physics3d.World, cfg Config, pos physics3d.Vec3, rot physics3d.Quat) (*Vehicle, error)New validates cfg, adds the chassis to world at pos with orientation rot, and returns the Vehicle. The chassis rests on its suspension once World.Step runs; place pos about RestLength + Radius above the ground below each anchor.
func (v *Vehicle) Checksum() uint64Checksum returns a deterministic 64-bit FNV-1a hash of v's chassis pose, velocities, steering, input, and all wheel states.
func (v *Vehicle) Config() ConfigConfig returns a copy of the car's tuning, as passed to New. The tuning is fixed for the Vehicle's lifetime; to drive with different tuning, remove the chassis from the world and create a new Vehicle.
func (v *Vehicle) Forward() physics3d.Vec3Forward returns the chassis' world-space forward axis (local -Z).
func (v *Vehicle) Grounded() intGrounded returns how many wheels touched the ground on the last Step.
func (v *Vehicle) Input() InputInput returns the input the next Step applies.
func (v *Vehicle) Reset(pos physics3d.Vec3, rot physics3d.Quat)Reset teleports the chassis to pos and rot, stops it, centers the steering and clears every wheel's contact, such as to respawn at a checkpoint.
func (v *Vehicle) Restore(snap Snapshot, world *physics3d.World) errorRestore restores v's steering, input, ray mask, and wheel states from snap. When world is non-nil, v.Body and each wheel's Ground pointer are relinked by body ID against world.Bodies().
func (v *Vehicle) Save() SnapshotSave captures a deep, deterministic, JSON-serializable snapshot of v.
func (v *Vehicle) SetInput(in Input)SetInput sets the input the next Step applies, clamping each axis to its range and treating NaN as 0. Input stays in effect until it is set again.
func (v *Vehicle) Speed() float32Speed returns the chassis' signed speed along Forward in m/s; negative while reversing.
func (v *Vehicle) Step(world *physics3d.World, dt time.Duration)Step advances the car's steering, suspension and tires by dt and applies their impulses to the chassis (and to dynamic bodies under the wheels). Call it once per fixed step, before World.Step.
func (v *Vehicle) Up() physics3d.Vec3Up returns the chassis' world-space up axis (local +Y).
func (v *Vehicle) WheelTransform(i int) (physics3d.Vec3, physics3d.Quat)WheelTransform returns wheel i's world-space center and orientation, including steering and spin, for drawing its mesh. The mesh's axle is its local X axis.
type Wheel struct {
// Config is a copy of the wheel's configuration, for reading; Step uses the Vehicle's own copy, so changing it has no effect.
Config WheelConfig
// Contact reports whether the wheel's ray touched ground on the last step.
Contact bool
// ContactPoint is the world-space point where the wheel touches the ground.
ContactPoint physics3d.Vec3
// ContactNormal is the ground's surface normal at ContactPoint.
ContactNormal physics3d.Vec3
// Ground is the body under the wheel, or nil for no contact or a triangle mesh or heightfield.
Ground *physics3d.Body
// SuspensionLength is the current suspension length, from 0 (fully compressed) to RestLength (fully extended).
SuspensionLength float32
// SuspensionForce is the suspension force in newtons pushing the chassis up on the last step.
SuspensionForce float32
// SteerAngle is the wheel's steering angle in radians about the chassis' up axis; positive turns left.
SteerAngle float32
// SpinSpeed is the wheel's rolling speed in radians per second; positive rolls forward.
SpinSpeed float32
// SpinAngle is the accumulated rolling angle in radians, wrapped to [-π, π].
SpinAngle float32
// Sliding reports whether the tire force hit its friction limit on the last step, such as for skid marks or tire squeal.
Sliding bool
}Wheel is one wheel's configuration and the state Vehicle.Step left it in.
type WheelConfig struct {
// Name identifies the wheel, such as "front-left"; names are unique within a Config.
Name string `yaml:"name"`
// Anchor is the top of the suspension in chassis space, relative to the center of mass.
Anchor [3]float32 `yaml:"anchor,flow"`
// Radius is the wheel radius (> 0).
Radius float32 `yaml:"radius"`
// RestLength is the suspension length with no load (>= 0); the wheel ray is RestLength + Radius long.
RestLength float32 `yaml:"restLength"`
// Stiffness is the spring rate in newtons per meter of compression (> 0).
Stiffness float32 `yaml:"stiffness"`
// Damping is the damper rate in newton-seconds per meter (>= 0).
Damping float32 `yaml:"damping"`
// MaxForce caps the suspension force in newtons; 0 leaves it uncapped.
MaxForce float32 `yaml:"maxForce,omitempty"`
// Friction is the tire's friction coefficient: the combined tire force stays within Friction times the wheel's load (>= 0).
Friction float32 `yaml:"friction"`
// Steer marks a wheel turned by steering input.
Steer bool `yaml:"steer,omitempty"`
// Drive marks a wheel driven by the engine.
Drive bool `yaml:"drive,omitempty"`
// Brake marks a wheel slowed by brake input.
Brake bool `yaml:"brake,omitempty"`
// Handbrake marks a wheel locked by the handbrake.
Handbrake bool `yaml:"handbrake,omitempty"`
}WheelConfig describes one wheel: where its suspension is mounted, its spring and damper, its tire and which inputs it receives.
type WheelSnapshot struct {
Contact bool `json:"contact,omitempty"`
ContactPoint physics3d.Vec3 `json:"contactPoint"`
ContactNormal physics3d.Vec3 `json:"contactNormal"`
GroundID int `json:"groundID,omitempty"`
SuspensionLength float32 `json:"suspensionLength"`
SuspensionForce float32 `json:"suspensionForce"`
SteerAngle float32 `json:"steerAngle"`
SpinSpeed float32 `json:"spinSpeed"`
SpinAngle float32 `json:"spinAngle"`
Sliding bool `json:"sliding,omitempty"`
}WheelSnapshot captures one wheel's dynamic runtime state.