# misc/steering2d (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/steering2d/

2D steering utility.

## Steering2D extends Object

2D steering utility.
- Gathers frequently reinvented steering calculations, like combat AI movement that "approaches when far, and keeps distance while circling left and right when within range",
  into pure functions. The return value is the desired velocity vector.

Example: Get an approach velocity and an orbit velocity

```js
import { Steering2D, Vector2 } from "./build/vanilla.js";

const position = Vector2.create(0, 0);
const targetPosition = Vector2.create(100, 0);
const seekVelocity = Steering2D.seek(position, targetPosition, 50);
console.log(seekVelocity.x, seekVelocity.y);

const orbitVelocity = Steering2D.orbitAtRange(position, targetPosition, 80, 50, 1.0);
console.log(orbitVelocity.x, orbitVelocity.y, orbitVelocity.length());
```

- `static seek(position, targetPosition, speed)` (static, since 0.3.0): Returns the velocity that approaches the target. (static)
  - `position` Vector2: Current position.
  - `targetPosition` Vector2: Target position.
  - `speed` number: Speed. (length of the returned vector)
  - returns Vector2: Velocity vector toward the target. (a zero vector if the two positions are nearly the same)
- `static orbitAtRange(position, targetPosition, preferredRange, speed, elapsedSeconds, strafeRate = 1.7)` (static, since 0.3.0): Returns the velocity that strafes while keeping range. (static)
  - Mixes in an approach component when farther than the range and a retreat component when closer,
    and adds a sin-wave left-right strafe along the tangent to create lively movement.
  - `position` Vector2: Current position.
  - `targetPosition` Vector2: Target position.
  - `preferredRange` number: Distance to keep.
  - `speed` number: Speed. (length of the returned vector)
  - `elapsedSeconds` number: Accumulated time used for the strafe phase.
  - `strafeRate` number: Angular speed of the strafe wave. (default 1.7)
  - returns Vector2: Desired velocity vector. (Its length is speed; (speed, 0) if the two positions are nearly the same; a zero vector if the desired direction is zero)

  Example: Circle around a target by passing the accumulated time every frame

  ```js
  import { Steering2D, Vector2 } from "./build/vanilla.js";
  
  const targetPosition = Vector2.create(0, 0);
  let position = Vector2.create(200, 0);
  let elapsedSeconds = 0;
  const timeDelta = 1 / 60;
  for (let frame = 0; frame < 180; ++frame) {
  	elapsedSeconds += timeDelta;
  	const velocity = Steering2D.orbitAtRange(position, targetPosition, 100, 80, elapsedSeconds);
  	const step = velocity.multiply(timeDelta);
  	position = position.add(step);
  }
  console.log(position.x, position.y, position.length());
  ```

