Skip to content

Commit

Permalink
More sensible units
Browse files Browse the repository at this point in the history
  • Loading branch information
ftripier committed Sep 3, 2018
1 parent 2563330 commit 511fd0e
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ function draw(state: State, ctx: CanvasRenderingContext2D) {
ctx.stroke();
}

const INITIAL_ANGULAR_VELOCITY = Math.PI * (1 / 128);
const INITIAL_ANGULAR_VELOCITY = Math.PI * (1 / 2);
const INITIAL_THETA = 0;

function evolveSystem(state: State, dt: number) {
Expand All @@ -108,15 +108,17 @@ function evolveSystem(state: State, dt: number) {

const oldTheta = state.system.theta;
const oldAngularVelocity = state.system.angularVelocity;
let newTheta = oldTheta + oldAngularVelocity * dt;
let newAngularVelocity = oldAngularVelocity + gravitationalAcceleration * dt;
let newTheta = oldTheta + oldAngularVelocity * (dt / 1000);
let newAngularVelocity =
oldAngularVelocity + gravitationalAcceleration * (dt / 1000);

// because of floating point error, the energy of the system rises over time.
// This corrects for these errors.
const potentialEnergy = (gravity: number, mass: number, theta: number) =>
-gravity * mass * Math.cos(theta);
const kineticEnergy = (mass: number, angularVelocity: number) =>
(mass * angularVelocity ** 2) / 2;

const currentEnergy = kineticEnergy(mass, newAngularVelocity);
const initialEnergy = kineticEnergy(mass, INITIAL_ANGULAR_VELOCITY);

Expand Down Expand Up @@ -149,7 +151,7 @@ function update(state: State) {
let dt = state.dt;
while (dt > 0) {
const expectedFrameTime = 16 + 2 / 3;
const normalizedDt = Math.max(dt, expectedFrameTime) / expectedFrameTime;
const normalizedDt = Math.max(dt, expectedFrameTime);
evolveSystem(state, normalizedDt);
dt -= expectedFrameTime;
}
Expand All @@ -162,7 +164,7 @@ const loop = (state: State, ctx: CanvasRenderingContext2D) => {
};
engine.nextFrame(loop);
window.requestAnimationFrame(engine.run.bind(engine));
const input = new Input("Gravity", "0.001", (e: Event) => {
const input = new Input("Gravity", "1", (e: Event) => {
engine.state.system.gravity = input.getValue();
});
engine.state.system.gravity = input.getValue();

0 comments on commit 511fd0e

Please sign in to comment.