Vectors
by Sam Fereday
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/victor/1.1.0/victor.min.js"></script>
<canvas id="canvas" width="300" height="300" />
CSS
html,
body {
margin: 0;
padding: 0;
background: #555;
}
canvas {
background: #000;
display: block
}
JavaScript
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const width = 300;
const height = 300;
const state = {
mousePos: {
x: 0,
y: 0
}
}
class Mover {
constructor(mass = 2, maxSpeed = 2) {
this.maxSpeed = new Victor(maxSpeed, maxSpeed);
this.mass = new Victor(mass, mass);
this.acceleration = new Victor(0, 0);
this.position = new Victor(width / 2, height / 2);
this.rotation = null;
}
applyForce(force) {
const f = force.clone();
f.divide(this.mass);
this.acceleration.add(f);
// Apply force
// copy vector
// divide the force by mass
// apply it to acceleration
// Too side-effecty
this.position.x += this.acceleration.x;
this.position.y += this.acceleration.y;
}
update(delta) {
var p = delta / 16
// this.updateRotation(p);
this.updateMovement(p);
}
updateMovement() {
// Reset vel for next tick
this.acceleration.x = 0;
this.acceleration.y = 0;
//
const target = Victor(state.mousePos.x, state.mousePos.y);
const position = Victor(this.position.x, this.position.y);
const current_velocity = Victor(this.acceleration.x, this.acceleration.y);
const desired_velocity = target.subtract(position)
.clone()
.normalize()
.multiply(this.maxSpeed);
const steering_velocity = desired_velocity.subtract(current_velocity)
.clone()
.divide(this.mass);
// Increment next velocity measure 'if' there is any.
const steering = current_velocity
.clone()
.add(steering_velocity)
.limit(10, .75);
console.log(steering);
this.applyForce(steering);
// Simulate some wind
//this.applyForce(new Victor(1.2, 0));
// FORCE
// acceleration = force; // no grav
// acc us equal to the sum of all forces divided by its mass (not weight)
// return from here, more immutable
}
}
const mover = new Mover();
function draw() {
...