motion

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 3 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package motion is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package motion provides deterministic, rate-independent 2D motion helpers for games that drive objects from Go code without scene files, sharing the exact math and semantics of sceneformat's built-in 2D motion behavior components:

  • Bullet: linear projectile motion with speed, acceleration, gravity, optional angle alignment and continuous swept bouncing off solid geometry.
  • Sine: periodic oscillation (sine, triangle, sawtooth, reverse_sawtooth, square) with phase and magnitude applied as drift-free deltas.
  • Rotate: angular velocity and angular acceleration in degrees per second.
  • Orbit: circular motion around a fixed point or moving target.
  • MoveTo: direct movement toward a target point with optional acceleration and solid stopping.
  • Wrap: toroidal edge wrapping across scene or camera view bounds.
  • Bound: clamping an object's edge box or origin inside bounds.
  • DestroyOutside: detecting when an object leaves expanded bounds.
  • Fade: fade-in, hold (wait) and fade-out opacity envelope.
  • Flash: timed on/off visibility blinking with base-alpha restoration.

All trigonometry uses internal/detmath so arm64, amd64 and wasm produce bit-for-bit identical trajectories. Constant-acceleration and closed-form stepping ensure fixed-rate simulations (such as 60 Hz vs 120 Hz) reach the same positions per simulated second.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func EvalWave

func EvalWave(wave WaveKind, u float64) float64

EvalWave evaluates wave at cycle position u (any finite real number) and returns a value in [-1, 1].

Types

type Bound

type Bound struct {
	// Edge keeps the object's full [x-Left, x+Right] x [y-Top, y+Bottom] box inside bounds;
	// when false, clamps only the origin (x, y).
	Edge bool
	// Enabled controls whether Apply clamps coordinates.
	Enabled bool
}

Bound clamps an object inside a rectangle, either by its edge extents or by its origin.

func NewBound

func NewBound(edge bool) Bound

NewBound returns an enabled Bound behavior.

func (*Bound) Apply

func (b *Bound) Apply(x, y float64, bounds Bounds, left, top, right, bottom float64) (nx, ny float64)

Apply clamps (x, y) to stay inside bounds. When Edge is true, (left, top, right, bottom) are the non-negative distances from the object's origin to its four box edges.

type Bounds

type Bounds struct {
	MinX, MinY float64
	MaxX, MaxY float64
}

Bounds is an axis-aligned 2D rectangle [MinX, MaxX] x [MinY, MaxY].

func (Bounds) Expand

func (b Bounds) Expand(margin float64) Bounds

Expand returns b widened outward by margin on all four sides (negative margin is treated as 0).

func (Bounds) Valid

func (b Bounds) Valid() bool

Valid reports whether b has positive finite width and height.

type Bullet

type Bullet struct {
	// Speed is the current scalar travel speed in points per second along Angle.
	Speed float64
	// Acceleration is the linear acceleration along the velocity direction in points/s^2.
	Acceleration float64
	// Gravity is the downward (+Y) acceleration in points/s^2.
	Gravity float64
	// Angle is the heading in degrees (0 = +X right, 90 = +Y down).
	Angle float64
	// SetAngle reports whether the object's rotation should track the heading.
	SetAngle bool
	// BounceOffSolids reflects velocity across solid surface normals when a SolidCastFunc is supplied.
	BounceOffSolids bool
	// Enabled controls whether Step advances the bullet.
	Enabled bool
	// contains filtered or unexported fields
}

Bullet advances a 2D projectile with speed, linear acceleration along its travel direction, vertical gravity (+Y down), optional orientation alignment and continuous bouncing off solids.

func NewBullet

func NewBullet(speed, acceleration, gravity, angleDeg float64, setAngle, bounceOffSolids bool) Bullet

NewBullet returns an enabled Bullet initialized from speed, acceleration, gravity and angle (degrees).

func (*Bullet) SetHeading

func (b *Bullet) SetHeading(angleDeg float64)

SetHeading updates the bullet's heading in degrees while preserving its current speed.

func (*Bullet) SetSpeed

func (b *Bullet) SetSpeed(speed float64)

SetSpeed updates the bullet's scalar speed while preserving its current heading.

func (*Bullet) Step

func (b *Bullet) Step(x, y float64, dt time.Duration, cast SolidCastFunc) BulletStepResult

Step advances the bullet from (x, y) by dt. When BounceOffSolids is true and cast is non-nil, the displacement is swept continuously against solids and reflected across the contact normal.

func (*Bullet) Velocity

func (b *Bullet) Velocity() (vx, vy float64)

Velocity returns the current (vx, vy) velocity in points per second.

type BulletStepResult

type BulletStepResult struct {
	X, Y      float64
	Rotation  float64
	SetRot    bool
	Bounced   bool
	Bounces   int
	HitNormal [2]float64
}

BulletStepResult reports the updated position, heading and bounce info for one Bullet.Step call.

type DestroyOutside

type DestroyOutside struct {
	// Margin is the distance outside the bounds an object may travel before being destroyed (>= 0).
	Margin float64
	// Enabled controls whether Outside returns true.
	Enabled bool
}

DestroyOutside tests whether an object has left a rectangle expanded by Margin.

func NewDestroyOutside

func NewDestroyOutside(margin float64) DestroyOutside

NewDestroyOutside returns an enabled DestroyOutside check.

func (*DestroyOutside) Outside

func (d *DestroyOutside) Outside(x, y float64, bounds Bounds) bool

Outside reports whether (x, y) lies strictly outside bounds expanded by Margin.

type Fade

type Fade struct {
	// FadeIn is the ramp-up duration from 0 to BaseAlpha in seconds (>= 0).
	FadeIn float64
	// Wait is the hold duration at BaseAlpha in seconds (>= 0).
	Wait float64
	// FadeOut is the ramp-down duration from BaseAlpha to 0 in seconds (>= 0).
	FadeOut float64
	// Destroy reports whether the owner should be freed upon completion.
	Destroy bool
	// BaseAlpha is the peak opacity in [0, 1] (0 defaults to 1 if BaseAlphaSet is false).
	BaseAlpha float64
	// Running controls whether Step advances the fade timer.
	Running bool
	// Enabled controls whether Step runs at all.
	Enabled bool
	// contains filtered or unexported fields
}

Fade drives an opacity envelope: FadeIn -> Wait -> FadeOut, optionally marking the object for destruction when finished.

func NewFade

func NewFade(fadeIn, wait, fadeOut float64, destroy, autostart bool) Fade

NewFade returns a Fade behavior configured with fadeIn, wait, fadeOut (seconds) and destroy flag.

func (*Fade) Alpha

func (f *Fade) Alpha() float64

Alpha returns the opacity at the current elapsed time without advancing.

func (*Fade) Start

func (f *Fade) Start()

Start restarts the fade envelope from elapsed = 0.

func (*Fade) Step

func (f *Fade) Step(dt time.Duration) FadeStepResult

Step advances the fade timer by dt and returns the current alpha and whether the fade finished on this step.

func (*Fade) Stop

func (f *Fade) Stop()

Stop pauses the fade envelope without resetting elapsed time.

type FadeStepResult

type FadeStepResult struct {
	Alpha         float64
	Finished      bool
	ShouldDestroy bool
}

FadeStepResult reports the computed opacity and completion flags for one Fade.Step call.

type Flash

type Flash struct {
	// On is the visible interval duration in seconds (>= 0).
	On float64
	// Off is the hidden interval duration in seconds (>= 0).
	Off float64
	// Enabled controls whether Step advances the flash.
	Enabled bool
	// contains filtered or unexported fields
}

Flash toggles visibility on and off for a requested duration, then restores visibility.

func NewFlash

func NewFlash(on, off float64) Flash

NewFlash returns an enabled (initially idle) Flash behavior.

func (*Flash) Active

func (f *Flash) Active() bool

Active reports whether the flash is currently running.

func (*Flash) Step

func (f *Flash) Step(dt time.Duration) FlashStepResult

Step advances the flash timer by dt and returns visibility and completion state.

func (*Flash) Stop

func (f *Flash) Stop()

Stop halts flashing immediately and restores visibility.

func (*Flash) Trigger

func (f *Flash) Trigger(duration float64)

Trigger starts flashing for duration seconds (<= 0 stops immediately).

func (*Flash) Visible

func (f *Flash) Visible() bool

Visible reports whether the object should currently be drawn.

type FlashStepResult

type FlashStepResult struct {
	Active   bool
	Visible  bool
	Finished bool
}

FlashStepResult reports whether the object should be visible and whether the flash ended on this step.

type MoveTo

type MoveTo struct {
	// MaxSpeed is the top speed in points per second (>= 0).
	MaxSpeed float64
	// Acceleration is the linear ramp-up in points/s^2 (0 reaches MaxSpeed immediately).
	Acceleration float64
	// StopOnSolids halts movement when a solid is encountered along the path.
	StopOnSolids bool
	// TargetX and TargetY are the current destination coordinates.
	TargetX, TargetY float64
	// Active reports whether the object is currently moving toward the target.
	Active bool
	// Enabled controls whether Step advances movement.
	Enabled bool
	// contains filtered or unexported fields
}

MoveTo drives an object straight toward (TargetX, TargetY) at up to MaxSpeed points per second, optionally accelerating smoothly and stopping on solid collisions.

func NewMoveTo

func NewMoveTo(maxSpeed, acceleration float64, stopOnSolids bool) MoveTo

NewMoveTo returns an enabled (initially idle) MoveTo behavior.

func (*MoveTo) SetTarget

func (m *MoveTo) SetTarget(tx, ty float64)

SetTarget assigns a new destination and starts moving toward it.

func (*MoveTo) Speed

func (m *MoveTo) Speed() float64

Speed returns the current instantaneous speed in points per second.

func (*MoveTo) Step

func (m *MoveTo) Step(x, y float64, dt time.Duration, cast SolidCastFunc) MoveToStepResult

Step advances from (x, y) toward (TargetX, TargetY) by dt using exact piecewise constant-acceleration integration (rate-independent across fixed step rates).

func (*MoveTo) Stop

func (m *MoveTo) Stop()

Stop halts movement and resets current speed to zero.

type MoveToStepResult

type MoveToStepResult struct {
	X, Y    float64
	Arrived bool
	Blocked bool
}

MoveToStepResult reports the updated position and arrival/block flags from one MoveTo.Step call.

type Orbit

type Orbit struct {
	// Radius is the orbit radius in points (>= 0).
	Radius float64
	// Speed is the angular velocity in degrees per second.
	Speed float64
	// Angle is the current orbit angle in degrees (0 = +X right, 90 = +Y down).
	Angle float64
	// SetAngle reports whether the object's rotation should match the orbit angle.
	SetAngle bool
	// Enabled controls whether Step advances the orbit.
	Enabled bool
}

Orbit moves an object along a circle of Radius around a center point at Speed degrees per second.

func NewOrbit

func NewOrbit(radius, speedDeg, angleDeg float64, setAngle bool) Orbit

NewOrbit returns an enabled Orbit behavior.

func (*Orbit) Step

func (o *Orbit) Step(centerX, centerY float64, dt time.Duration) OrbitStepResult

Step advances the orbit angle by dt and computes the object's new position around (centerX, centerY).

type OrbitStepResult

type OrbitStepResult struct {
	X, Y     float64
	Rotation float64
	SetRot   bool
}

OrbitStepResult holds the updated position and optional rotation from one Orbit.Step call.

type Rotate

type Rotate struct {
	// Speed is the angular velocity in degrees per second (positive = clockwise in Y-down 2D).
	Speed float64
	// Acceleration is the angular acceleration in degrees per second squared.
	Acceleration float64
	// Enabled controls whether Step advances the rotation.
	Enabled bool
}

Rotate spins an object continuously at Speed degrees per second with optional angular Acceleration.

func NewRotate

func NewRotate(speedDeg, accelDeg float64) Rotate

NewRotate returns an enabled Rotate behavior.

func (*Rotate) Step

func (r *Rotate) Step(dt time.Duration) (deltaRad float64)

Step advances the angular velocity by dt using exact constant-acceleration integration and returns the incremental rotation in radians to add to the object's rotation.

type Sine

type Sine struct {
	// Period is the duration of one full oscillation cycle in seconds (> 0).
	Period float64
	// Magnitude is the peak amplitude in property units (points, degrees, scale, or alpha).
	Magnitude float64
	// Wave selects the periodic waveform (defaults to WaveSine when empty).
	Wave WaveKind
	// Phase is the initial cycle offset (0.25 = quarter period, 0.5 = half period).
	Phase float64
	// Enabled controls whether Step advances the oscillation.
	Enabled bool
	// contains filtered or unexported fields
}

Sine oscillates a scalar quantity periodically around its authored baseline using additive deltas, so it composes cleanly with other behaviors (such as Bullet).

func NewSine

func NewSine(period, magnitude float64, wave WaveKind, phase float64) Sine

NewSine returns an enabled Sine oscillator.

func (*Sine) Elapsed

func (s *Sine) Elapsed() float64

Elapsed returns the accumulated simulated time in seconds.

func (*Sine) Reset

func (s *Sine) Reset()

Reset sets elapsed time and applied offset back to zero.

func (*Sine) Step

func (s *Sine) Step(dt time.Duration) (delta float64)

Step advances the oscillator by dt and returns the incremental delta (newValue - lastValue) to add to the target property.

func (*Sine) Value

func (s *Sine) Value() float64

Value returns the current oscillation offset at the accumulated elapsed time.

type SolidCastFunc

type SolidCastFunc func(x, y, dx, dy float64) (SolidHit, bool)

SolidCastFunc sweeps an object from (x, y) by displacement (dx, dy) and reports the earliest solid hit in [0, 1], if any.

type SolidHit

type SolidHit struct {
	// Fraction is the normalized time of impact in [0, 1].
	Fraction float64
	// NormalX and NormalY form the unit surface normal pointing out of the solid.
	NormalX, NormalY float64
}

SolidHit is the earliest continuous contact along a motion sweep from (x, y) by (dx, dy).

type WaveKind

type WaveKind string

WaveKind identifies the periodic waveform used by Sine.

const (
	// WaveSine oscillates as sin(2*pi*u) in [-1, 1].
	WaveSine WaveKind = "sine"
	// WaveTriangle oscillates linearly from 0 -> 1 -> -1 -> 0 in [-1, 1].
	WaveTriangle WaveKind = "triangle"
	// WaveSawtooth ramps linearly from -1 to +1 over each period, jumping back to -1 at u = 1.
	WaveSawtooth WaveKind = "sawtooth"
	// WaveReverseSawtooth ramps linearly from +1 to -1 over each period, jumping back to +1 at u = 1.
	WaveReverseSawtooth WaveKind = "reverse_sawtooth"
	// WaveSquare holds +1 for the first half of each period [0, 0.5) and -1 for [0.5, 1).
	WaveSquare WaveKind = "square"
)

type Wrap

type Wrap struct {
	// Margin expands the wrap rectangle outward on all four sides (>= 0).
	Margin float64
	// Enabled controls whether Apply wraps coordinates.
	Enabled bool
}

Wrap wraps coordinates leaving one side of a rectangle onto the opposite side, preserving overshoot so wrapped motion stays rate-independent.

Example

Wrap carries an object that leaves one side of the play area onto the opposite side, preserving the overshoot so wrapped motion stays rate-independent.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/motion"
)

func main() {
	bounds := motion.Bounds{MinX: 0, MinY: 0, MaxX: 100, MaxY: 50}
	wrap := motion.NewWrap(0)
	x, y, wrapped := wrap.Apply(130, -10, bounds)
	fmt.Println(x, y, wrapped)
}
Output:
30 40 true

func NewWrap

func NewWrap(margin float64) Wrap

NewWrap returns an enabled Wrap behavior.

func (*Wrap) Apply

func (w *Wrap) Apply(x, y float64, bounds Bounds) (nx, ny float64, wrapped bool)

Apply wraps (x, y) into bounds expanded by Margin and reports whether wrapping occurred.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL