Velocity
A velocity tracker that calculates speed based on position changes over time.
This class tracks position samples over a time window and calculates velocity based on the distance traveled divided by the elapsed time. It's commonly used for touch/drag interactions to determine fling velocity or for any motion that needs velocity tracking.
The tracker automatically prunes old samples outside a 150ms window to ensure velocity calculations remain responsive to recent motion.
Example usage:
var velocity = new Velocity();
// During drag/motion updates
velocity.add(currentPosition);
// When motion ends
var speed = velocity.get(); // pixels per second
// Apply inertia based on velocity
if (Math.abs(speed) > threshold) {
startInertiaAnimation(speed);
}
Instance Members
reset(): Void
Reset the velocity tracker, clearing all position and time samples. After calling this, get() will return 0 until new samples are added.
Add a position sample to the velocity tracker.
Name | Type | Default | Description |
---|---|---|---|
position |
Float | The current position value (e.g., x or y coordinate) | |
minusDelta |
Float | 0 |
Optional time offset in seconds to subtract from the current time. Useful when the position data is slightly delayed. |
get(): Float
Calculate the current velocity based on recent position samples.
The velocity is calculated as the distance between the first and last samples divided by the time elapsed, using samples from the last 150ms.
Returns | Description |
---|---|
Float | The velocity in units per second (e.g., pixels per second). Returns 0 if there are fewer than 2 samples. |
new(): Void
Create a new velocity tracker.
Private Members
Array storing position samples.
Array storing the time (in seconds) when each position was recorded.
Remove position samples older than the specified time. This keeps the velocity calculation based on recent motion only.
Name | Type | Description |
---|---|---|
expireTime |
Float | The time threshold - samples older than this are removed |
toString(): String
Get a string representation of the current velocity.
Returns | Description |
---|---|
String | The current velocity as a string |