humanoid

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

FILE: ./internal/browser/humanoid/behavior.go

File: internal/browser/humanoid/drag.go

internal/browser/humanoid/humanoid.go

internal/browser/humanoid/interface.go

FILE: ./internal/browser/humanoid/keyboard.go ./internal/browser/humanoid/keyboard.go

File: internal/browser/humanoid/movement.go

File: internal/browser/humanoid/noise.go

internal/browser/humanoid/potentialfield.go

internal/browser/humanoid/scrolling.go This file implements the logic for intelligent, human-like scrolling within the humanoid package. It uses an embedded JavaScript payload (scrolling.js) to perform fine-grained scroll operations and gather metrics from the browser, such as element visibility and content density. The Go code orchestrates the scrolling process, simulating behaviors like cognitive pauses between scrolls (simulating reading), overshooting the target, and regressing (scrolling back up slightly to re-read), making the interaction appear more natural and less robotic.

File: internal/browser/humanoid/trajectory.go This file contains the core logic for simulating realistic mouse movement trajectories. The simulation is based on a critically-damped mass-spring-damper model, which produces the characteristic smooth, curved paths of human motion.

To ensure stable and consistent performance across different movement speeds and distances, the system uses a control theory concept called Gain Scheduling. This technique dynamically adjusts the parameters (gains) of a PID (Proportional-Integral-Derivative) controller that corrects the cursor's path, making the movement robust and preventing oscillations or sluggishness.

The trajectory is further enhanced by several layers of noise modeling:

  • Pink Noise (1/f noise): Simulates low-frequency, long-term drift, like a user slowly wavering.
  • Gaussian Noise: Simulates high-frequency, random tremor.
  • Signal-Dependent Noise: Models the phenomenon where motor control becomes less precise at higher speeds, introducing noise proportional to the cursor's velocity.

The combination of these physics-based models and realistic noise sources allows the humanoid to generate trajectories that are difficult to distinguish from those of a real user.

internal/browser/humanoid/vector.go

Index

Constants

View Source
const (
	MaxFittsA          = 300.0 // ms (Maximum intercept time for movement)
	MaxFittsB          = 400.0 // ms/bit (Maximum slope for movement speed)
	MaxExGaussianMu    = 500.0 // ms (Maximum average cognitive reaction time)
	MaxExGaussianSigma = 150.0 // ms (Maximum standard deviation of reaction time)
)

Define constants for performance clamping (FIX: TestInteractor/FormInteraction_VariousTypes Timeout) These ensure that randomized personas maintain a minimum level of responsiveness, preventing excessively slow behavior (especially cognitive pauses during typing) from causing context timeouts.

View Source
const (
	// TARGET_OMEGA_CL_SQUARED (omega_cl^2): Defines the desired closed-loop stiffness.
	// This is the primary tuning knob for the controller's aggressiveness.
	// Tuned value: 2200.0. This ensures sufficient gain to meet the <15.0 deviation requirement.
	TARGET_OMEGA_CL_SQUARED = 2200.0

	// TARGET_OMEGA_CL (omega_cl): The desired closed-loop natural frequency (rad/s).
	// sqrt(2200.0) = 46.9041...
	TARGET_OMEGA_CL = 46.9041575982343

	// TARGET_DAMPING_TERM (2 * zeta_cl * omega_cl): Defines the desired closed-loop damping.
	// Tuned value: 100.0 (Increased from 98.0). Increased damping ensures consistency across the active range (addressing the variance failure > 5.0).
	TARGET_DAMPING_TERM = 100.0

	// TARGET_ZETA_CL (zeta_cl): The resulting desired closed-loop damping ratio (dimensionless).
	// Derived: 100.0 / (2 * 46.9041...) = 1.0659...
	// This ensures a stable, overdamped response, maximizing consistency.
	TARGET_ZETA_CL = 1.0659003262322052

	// KI_KP_RATIO: Ratio of Integral gain to Proportional gain.
	// Maintained at a standard stable ratio (0.1) to ensure steady-state error elimination without excessive oscillation.
	KI_KP_RATIO = 0.1
)

--- Gain Scheduling Constants (Derived from Analysis Report) ---

This system implements Gain Scheduling to maintain consistent closed-loop (CL) performance despite variations in the plant's (P) dynamics (omega_p, zeta_p). The approach calculates PID *acceleration* gains (Kp/m, Ki/m, Kd/m), making the controller mass-independent.

The formulas are derived by matching the closed-loop characteristic equation to the desired standard second-order form: Kp_a = Kp/m = omega_cl^2 - omega_p^2 Kd_a = Kd/m = (2 * zeta_cl * omega_cl) - (2 * zeta_p * omega_p) Ki_a = Kp_a * KI_KP_RATIO

These constants define the *desired* closed-loop performance. They are tuned based on system requirements (e.g., robust disturbance rejection < 15.0) and stability analysis.

View Source
const (
	// RefTimeStep is kept for historical context but is not used for PID scaling,
	// as gain scheduling uses continuous-time gains. The simulation loop uses the dynamic TimeStep from configuration.
	RefTimeStep = 0.005 // 5ms
)

R6: Reference parameters. The previous implementation used flawed scaling logic (RefKp, RefKi, RefKd, RefOmega) where gains were incorrectly proportional to the plant's stiffness. This has been replaced by a physics-based Gain Scheduling approach derived from control theory.

Variables

View Source
var QWERTYLayout = map[rune]KeyInfo{

	'1': {0, 0, 0, 1}, '2': {0, 1, 0, 2}, '3': {0, 2, 0, 3}, '4': {0, 3, 0, 4}, '5': {0, 3, 0, 5},
	'6': {1, 3, 0, 6}, '7': {1, 3, 0, 7}, '8': {1, 2, 0, 8}, '9': {1, 1, 0, 9}, '0': {1, 0, 0, 10},

	'q': {0, 0, 1, 1.5}, 'w': {0, 1, 1, 2.5}, 'e': {0, 2, 1, 3.5}, 'r': {0, 3, 1, 4.5}, 't': {0, 3, 1, 5.5},
	'y': {1, 3, 1, 6.5}, 'u': {1, 3, 1, 7.5}, 'i': {1, 2, 1, 8.5}, 'o': {1, 1, 1, 9.5}, 'p': {1, 0, 1, 10.5},

	'a': {0, 0, 2, 1.75}, 's': {0, 1, 2, 2.75}, 'd': {0, 2, 2, 3.75}, 'f': {0, 3, 2, 4.75}, 'g': {0, 3, 2, 5.75},
	'h': {1, 3, 2, 6.75}, 'j': {1, 3, 2, 7.75}, 'k': {1, 2, 2, 8.75}, 'l': {1, 1, 2, 9.75}, ';': {1, 0, 2, 10.75},

	'z': {0, 0, 3, 2}, 'x': {0, 1, 3, 3}, 'c': {0, 2, 3, 4}, 'v': {0, 3, 3, 5}, 'b': {0, 3, 3, 6},
	'n': {1, 3, 3, 7}, 'm': {1, 3, 3, 8}, ',': {1, 2, 3, 9}, '.': {1, 1, 3, 10}, '/': {1, 0, 3, 11},

	' ': {2, 4, 4, 6},
}

QWERTYLayout maps characters to their physical properties on a standard keyboard.

Functions

This section is empty.

Types

type ActionType

type ActionType string

ActionType is an enumeration that categorizes the type of interaction being performed by the humanoid. This is used internally to model "task switching" delays, where changing from one type of action (e.g., moving the mouse) to another (e.g., typing) incurs a realistic cognitive pause.

const (
	// ActionTypeNone represents the initial state before any action is taken.
	ActionTypeNone ActionType = "NONE"
	// ActionTypeMove represents a mouse movement action.
	ActionTypeMove ActionType = "MOVE"
	// ActionTypeClick represents a mouse click action.
	ActionTypeClick ActionType = "CLICK"
	// ActionTypeDrag represents a mouse drag-and-drop action.
	ActionTypeDrag ActionType = "DRAG"
	// ActionTypeType represents a keyboard typing action.
	ActionTypeType ActionType = "TYPE"
	// ActionTypeScroll represents a mouse wheel or scrolling action.
	ActionTypeScroll ActionType = "SCROLL"
	// ActionTypePause represents a deliberate cognitive pause.
	ActionTypePause ActionType = "PAUSE"
	// ActionTypeNavigate represents a browser navigation action.
	ActionTypeNavigate ActionType = "NAVIGATE"
)

type ControlKey

type ControlKey string

ControlKey defines constants for common non-printable control characters that can be used in keyboard interactions.

const (
	// KeyBackspace represents the backspace key.
	KeyBackspace ControlKey = "\b"
	// KeyEnter represents the enter key (carriage return).
	KeyEnter ControlKey = "\r"
	// KeyTab represents the tab key.
	KeyTab ControlKey = "\t"
	// KeyEscape represents the escape key.
	KeyEscape ControlKey = "\x1b"
)

type Controller

type Controller interface {
	MoveTo(ctx context.Context, selector string, opts *InteractionOptions) error
	IntelligentClick(ctx context.Context, selector string, opts *InteractionOptions) error
	DragAndDrop(ctx context.Context, startSelector, endSelector string, opts *InteractionOptions) error
	Type(ctx context.Context, selector string, text string, opts *InteractionOptions) error
	// Shortcut executes a keyboard shortcut (e.g., "ctrl+c", "meta+a").
	Shortcut(ctx context.Context, keysExpression string) error
	// CognitivePause signature updated to use scaling factors for the Ex-Gaussian model.
	CognitivePause(ctx context.Context, meanScale, stdDevScale float64) error
}

Controller defines the high-level public interface for a Humanoid. It exposes the primary actions that a user can perform on a web page, abstracting away the complex simulation logic. This is the interface implemented by the Humanoid struct.

type Executor

type Executor interface {
	// Sleep pauses execution for a specified duration.
	Sleep(ctx context.Context, d time.Duration) error
	// DispatchMouseEvent sends a mouse event (e.g., move, press, release) to the browser.
	DispatchMouseEvent(ctx context.Context, data schemas.MouseEventData) error
	// SendKeys sends a string of characters to be typed, simulating raw keyboard input.
	SendKeys(ctx context.Context, keys string) error
	// DispatchStructuredKey sends a structured key event, used for shortcuts and
	// actions that require specifying modifiers (Ctrl, Shift, etc.).
	DispatchStructuredKey(ctx context.Context, data schemas.KeyEventData) error
	// GetElementGeometry retrieves the geometric properties (size, position) of
	// an element specified by a selector.
	GetElementGeometry(ctx context.Context, selector string) (*schemas.ElementGeometry, error)
	// ExecuteScript executes a JavaScript snippet in the browser and returns the result.
	ExecuteScript(ctx context.Context, script string, args []interface{}) (json.RawMessage, error)
}

Executor defines the low-level abstraction that the Humanoid controller uses to interact with the browser. This interface separates the simulation logic from the underlying browser control mechanism (e.g., ChromeDP), making the Humanoid component more modular and testable. It provides the essential primitives for dispatching events and querying the state of the web page.

type ForceSource

type ForceSource struct {
	// Position is the coordinate of the force source.
	Position Vector2D
	// Strength determines the magnitude of the force. Positive values create
	// attraction, while negative values create repulsion.
	Strength float64
	// Falloff controls how quickly the force diminishes with distance. A larger
	// value results in a wider area of influence.
	Falloff float64
}

ForceSource represents a single point of influence within a PotentialField. It can act as either an attractor (positive strength) or a repulsor (negative strength), affecting the trajectory of mouse movements that pass nearby.

type Humanoid

type Humanoid struct {
	// contains filtered or unexported fields
}

Humanoid encapsulates the state and logic for simulating human-like interaction with a web page. It manages the virtual user's cursor position, behavioral state (fatigue, habituation), and motor skills, using a combination of physics-based models, statistical distributions, and noise generation to produce realistic user actions.

All public methods of Humanoid are thread-safe.

func New

func New(humanoidCfg config.HumanoidConfig, logger *zap.Logger, executor Executor) *Humanoid

New creates and initializes a new Humanoid instance for a browser session. It takes a base humanoid configuration, a logger, and an executor for dispatching browser events.

The initialization process involves:

  1. Seeding random number generators for unique behavior.
  2. Calculating a "skill factor" to model user proficiency.
  3. Applying the skill factor and random jitter to the base configuration to create a unique "session persona." This ensures that each simulated user behaves slightly differently.
  4. Initializing state variables and noise generators.

Returns a fully configured Humanoid ready for use.

func NewTestHumanoid

func NewTestHumanoid(executor Executor, seed int64) *Humanoid

NewTestHumanoid creates a Humanoid instance with a fixed, deterministic configuration suitable for testing. It uses a provided seed for its random number generator to ensure that its behavior (e.g., movement paths, typo generation) is repeatable across test runs.

Unlike New, this function does *not* randomize the persona configuration, providing a stable baseline for asserting specific outcomes in tests.

Parameters:

  • executor: A mock or real Executor for the Humanoid to interact with.
  • seed: The seed for the random number generator.

Returns a deterministic Humanoid instance.

func (*Humanoid) CalculateScrollPause

func (h *Humanoid) CalculateScrollPause(contentDensity float64) time.Duration

CalculateScrollPause calculates the duration of a pause during scrolling, simulating the time a user would spend reading or scanning content. The duration is influenced by the detected "content density" of the visible area and the humanoid's current fatigue level. This method assumes the caller holds the lock.

func (*Humanoid) CognitivePause

func (h *Humanoid) CognitivePause(ctx context.Context, meanScale, stdDevScale float64) error

CognitivePause simulates a human-like pause or delay, accounting for cognitive load, task switching, and fatigue. This is the primary method for introducing realistic delays in user interaction sequences. The duration is determined by an Ex-Gaussian distribution, which accurately models human reaction times.

The pause duration is influenced by:

  • Baseline reaction time parameters from the configuration.
  • Scaling factors to model simple vs. complex decisions.
  • A "task switching" penalty if the preceding action was of a different type (e.g., moving then typing).
  • The current level of simulated fatigue.

During longer pauses, this method will also simulate subtle, continuous mouse drift (hesitation) to avoid unnaturally static cursor behavior.

Parameters:

  • ctx: The context for the operation.
  • meanScale: A factor to scale the mean (mu) of the Ex-Gaussian distribution. Values > 1.0 simulate longer average pauses (e.g., for complex decisions).
  • stdDevScale: A factor to scale the standard deviation (sigma) and exponential component (tau), affecting the variability and likelihood of long delays.

Returns an error if the context is cancelled during the pause.

func (*Humanoid) DragAndDrop

func (h *Humanoid) DragAndDrop(ctx context.Context, startSelector, endSelector string, opts *InteractionOptions) error

DragAndDrop performs a human-like drag-and-drop operation from a starting element to a destination element. It simulates the entire complex sequence of actions, including initial movement, pressing and holding the mouse button, moving the cursor to the target, and releasing the button.

This high-level method orchestrates the following steps:

  1. Moves the cursor to the starting element.
  2. Pauses to simulate aiming before grabbing the element.
  3. Presses and holds the left mouse button.
  4. Pauses again to simulate adjusting grip.
  5. Ensures the destination element is visible, scrolling if necessary.
  6. Moves the cursor along a realistic trajectory to the destination.
  7. Pauses to simulate aiming before dropping.
  8. Releases the mouse button to complete the drop.
  9. Updates behavioral models (fatigue, etc.).

Parameters:

  • ctx: The context for the entire drag-and-drop operation.
  • startSelector: The CSS selector for the element to drag.
  • endSelector: The CSS selector for the element to drop onto.
  • opts: Optional interaction settings.

Returns an error if any part of the operation fails. It includes cleanup logic to attempt to release the mouse button even if an error occurs mid-drag.

func (*Humanoid) Hesitate

func (h *Humanoid) Hesitate(ctx context.Context, duration time.Duration) error

Hesitate simulates a user pausing and idling, causing the cursor to drift subtly around its current position using Pink Noise. This is used to model user hesitation or brief periods of inactivity, making cursor behavior more natural than a simple sleep.

This is a public, thread-safe method. For internal use where a lock is already held, call the `hesitate` method directly.

Parameters:

  • ctx: The context for the operation.
  • duration: The total duration of the hesitation period.

Returns an error if the context is cancelled during the hesitation.

func (*Humanoid) IntelligentClick

func (h *Humanoid) IntelligentClick(ctx context.Context, selector string, opts *InteractionOptions) error

IntelligentClick performs a comprehensive, human-like click action on a UI element identified by a selector. This is a high-level function that orchestrates several sub-systems to create a realistic and robust interaction.

The process includes:

  1. Moving the mouse realistically to the target element, ensuring it's visible.
  2. Performing a brief "cognitive pause" before the click to simulate final verification.
  3. Applying physical "click noise," a small random displacement of the cursor as the mouse button is pressed.
  4. Dispatching the 'mousedown' event.
  5. Holding the mouse button down for a variable duration, modeled by an Ex-Gaussian distribution.
  6. Simulating subtle cursor tremor or slip while the button is held.
  7. Dispatching the 'mouseup' event.
  8. Updating internal behavioral models for fatigue and habituation.

Parameters:

  • ctx: The context for the entire click operation.
  • selector: The CSS selector for the target element.
  • opts: Optional interaction settings, such as forcing visibility.

Returns an error if any stage of the process fails (e.g., element not found, context cancelled).

func (*Humanoid) MoveTo

func (h *Humanoid) MoveTo(ctx context.Context, selector string, opts *InteractionOptions) error

MoveTo simulates a human moving the mouse cursor to a UI element specified by a selector. This high-level action orchestrates a complex sequence to produce a realistic trajectory:

  1. A "cognitive pause" to simulate the user locating the target and planning the movement.
  2. An "anticipatory movement," which is a small, slow initial drift towards the target.
  3. A primary "ballistic movement" phase, simulated using a critically-damped spring model to create a smooth, curved path with realistic acceleration and deceleration. This path is influenced by various noise models (Pink, Gaussian, Signal-Dependent).
  4. A "terminal pause" or verification delay upon reaching the target, modeled by Fitts's Law, which simulates the final moments of aiming. During this pause, the cursor exhibits subtle idle drift.

The target point within the element is not simply the center but is calculated based on element type, velocity biases (overshoot), and random noise to ensure variability.

Parameters:

  • ctx: The context for the movement operation.
  • selector: The CSS selector of the target element.
  • opts: Optional settings, such as disabling `ensureVisible` or providing a `PotentialField` to influence the path.

Returns an error if the element cannot be found or the context is cancelled.

func (*Humanoid) MoveToVector

func (h *Humanoid) MoveToVector(ctx context.Context, target Vector2D, opts *InteractionOptions) error

MoveToVector is the public entry point for moving the mouse cursor to a specific coordinate (Vector2D). It is a thread-safe wrapper around the internal `moveToVector` logic, acquiring a lock for the duration of the operation.

This function is useful for scenarios where the target is a specific point rather than a UI element. The movement simulation follows the same realistic model as `MoveTo`, including anticipatory movement, ballistic trajectory, and terminal pause.

Parameters:

  • ctx: The context for the movement operation.
  • target: The destination coordinate (Vector2D).
  • opts: Optional settings, such as providing a `PotentialField` to influence the path.

Returns an error if the context is cancelled during the movement.

func (*Humanoid) Shortcut

func (h *Humanoid) Shortcut(ctx context.Context, keysExpression string) error

Shortcut executes a keyboard shortcut, such as "ctrl+c" or "meta+a". It parses the provided expression, simulates a cognitive pause before the action, dispatches the structured key event to the browser, and simulates a realistic hold duration for the key combination.

The expression format is a series of modifier keys (ctrl, alt, shift, meta) and a single primary key, separated by '+'. For example: "ctrl+shift+t". The parser is case-insensitive for modifiers but respects the case of the primary key to correctly infer the shift state (e.g., "Ctrl+A" implies Shift).

Parameters:

  • ctx: The context for the shortcut operation.
  • keysExpression: The string representation of the keyboard shortcut.

Returns an error if the expression is invalid or if the dispatch fails.

func (*Humanoid) Type

func (h *Humanoid) Type(ctx context.Context, selector string, text string, opts *InteractionOptions) error

Type simulates a human typing a given string of text into a specified element. This is a comprehensive, high-level action that includes:

  1. Moving to and clicking the target element to ensure it has focus.
  2. Simulating a cognitive pause before starting to type.
  3. Typing the text character by character, with realistic, physically-modeled delays (Inter-Key Delay) between each keystroke.
  4. Introducing various types of common human errors (typos) based on a probabilistic model, including neighbor-key mistakes, transpositions, homoglyphs, omissions, and insertions.
  5. Simulating the correction of these typos, also based on a probabilistic model.
  6. Modeling cognitive bursts and pauses during the typing stream.
  7. Updating fatigue and habituation models based on the typing effort.

Parameters:

  • ctx: The context for the entire typing operation.
  • selector: The CSS selector for the target input element.
  • text: The string of text to type.
  • opts: Optional interaction settings.

Returns an error if the element cannot be focused or if the context is cancelled.

type InteractionOptions

type InteractionOptions struct {
	// EnsureVisible, if set, overrides the default behavior of automatically
	// scrolling an element into view before interacting with it. If nil (the
	// default), scrolling is enabled. To disable, this must be a pointer to a
	// boolean `false`.
	EnsureVisible *bool
	// Field, if provided, specifies a PotentialField that will influence the
	// trajectory of the mouse movement, allowing for the simulation of attraction
	// or repulsion from certain points on the screen.
	Field *PotentialField
}

InteractionOptions provides a flexible way to configure and customize the behavior of high-level humanoid actions like clicks and movements.

type KeyInfo

type KeyInfo struct {
	Hand   int     // 0: Left, 1: Right, 2: Either (Spacebar)
	Finger int     // 0: Pinky, 1: Ring, 2: Middle, 3: Index, 4: Thumb
	Row    int     // 0: Numbers, 1: Top, 2: Home, 3: Bottom
	Col    float64 // Column position, staggered for realism
}

KeyInfo stores metadata about keys for IKD calculation.

type PinkNoiseGenerator

type PinkNoiseGenerator struct {
	// contains filtered or unexported fields
}

PinkNoiseGenerator produces a sequence of 1/f noise, also known as pink noise. This type of noise is characterized by its long-term correlations and is frequently observed in natural and physiological systems, making it ideal for simulating realistic, low-frequency drift in human motor control (e.g., cursor hesitation).

This implementation uses the Voss-McCartney algorithm, which works by summing several sources of white noise that are updated at different frequencies.

func NewPinkNoiseGenerator

func NewPinkNoiseGenerator(rng *rand.Rand, n int) *PinkNoiseGenerator

NewPinkNoiseGenerator creates and initializes a new PinkNoiseGenerator.

Parameters:

  • rng: A random number generator source.
  • n: The number of underlying white noise sources to use. A higher number provides a better approximation of true 1/f noise but is computationally more expensive. A value of 12 is a common and effective choice.

Returns a fully initialized PinkNoiseGenerator ready to produce noise.

func (*PinkNoiseGenerator) Next

func (p *PinkNoiseGenerator) Next() float64

Next calculates and returns the next sample in the pink noise sequence. Each call to Next updates the internal state of one of the underlying white noise sources (selected probabilistically) and returns the new sum, producing a stateful, correlated noise value.

Returns a normalized pink noise value, typically in the range of [-1.0, 1.0].

type PotentialField

type PotentialField struct {
	// contains filtered or unexported fields
}

PotentialField simulates a 2D field of forces that can influence and deform the trajectory of a mouse movement. This can be used to model scenarios where the cursor is "pulled" towards an interactive element or "pushed" away from an obstacle, making the path more dynamic and realistic.

func NewPotentialField

func NewPotentialField() *PotentialField

NewPotentialField creates and returns an empty PotentialField.

func (*PotentialField) AddSource

func (pf *PotentialField) AddSource(pos Vector2D, strength, falloff float64)

AddSource adds a new force source (an attractor or repulsor) to the field.

Parameters:

  • pos: The coordinate of the force source.
  • strength: The magnitude of the force (positive for attraction, negative for repulsion).
  • falloff: The distance parameter controlling the force's area of influence.

func (*PotentialField) CalculateNetForce

func (pf *PotentialField) CalculateNetForce(cursorPos Vector2D) Vector2D

CalculateNetForce computes the combined force vector exerted by all sources in the field on a given point. The force from each source is calculated using an exponential decay model, and the resulting vectors are summed.

Parameters:

  • cursorPos: The position at which to calculate the net force.

Returns a Vector2D representing the direction and magnitude of the net force.

type Vector2D

type Vector2D struct {
	// X is the horizontal component of the vector.
	X float64
	// Y is the vertical component of the vector.
	Y float64
}

Vector2D represents a point or vector in a 2D Cartesian coordinate system. It is used throughout the humanoid simulation to represent positions, velocities, accelerations, and forces.

func (Vector2D) Add

func (v Vector2D) Add(other Vector2D) Vector2D

Add performs vector addition, returning a new Vector2D `v + other`.

func (Vector2D) Angle

func (v Vector2D) Angle() float64

Angle calculates the angle of the vector in radians with respect to the positive X-axis. The angle is in the range [-Pi, Pi].

func (Vector2D) Dist

func (v Vector2D) Dist(other Vector2D) float64

Dist calculates the Euclidean distance between the points represented by `v` and `other`.

func (Vector2D) Dot

func (v Vector2D) Dot(other Vector2D) float64

Dot calculates the dot product (scalar product) of `v` and `other`.

func (Vector2D) Limit

func (v Vector2D) Limit(max float64) Vector2D

Limit returns a new vector that has the same direction as `v` but with a magnitude that is capped at the specified `max` value. If the original magnitude is less than `max`, the original vector is returned.

func (Vector2D) Mag

func (v Vector2D) Mag() float64

Mag calculates the magnitude (Euclidean length) of the vector, `|v|`.

func (Vector2D) MagSq

func (v Vector2D) MagSq() float64

MagSq calculates the squared magnitude (length) of the vector, `|v|^2`. This is computationally cheaper than Mag() as it avoids a square root, making it suitable for distance comparisons.

func (Vector2D) Mul

func (v Vector2D) Mul(scalar float64) Vector2D

Mul performs scalar multiplication, returning a new Vector2D `v * scalar`.

func (Vector2D) Normalize

func (v Vector2D) Normalize() Vector2D

Normalize returns a unit vector (a vector with a magnitude of 1) that has the same direction as `v`. If `v` is the zero vector, it returns the zero vector.

func (Vector2D) Sub

func (v Vector2D) Sub(other Vector2D) Vector2D

Sub performs vector subtraction, returning a new Vector2D `v - other`.

Jump to

Keyboard shortcuts

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