Skip to content

Advanced

Applying forces to many things

Use the regular Javascript constructs to apply forces to many objects.

// Initial things
let things = [ /* lots of things */ ]
// Things now contains a set of things after force has been applied
things = things.map(t => Forces.apply(t, gravityForce));

Dynamic

At times the pattern of initialising a force once and then reusing it repeatedly isn’t appropriate. For example, if you want friction to be affected by a ‘smoothness’ property you have defined, this won’t work:

const thing = {
position: Points.random(),
smoothness: Math.random(),
mass: 1
};
// Init force
const friction = Forces.velocityForce(0.00001, `multiply`);
const loop() => {
// When applying force it will use the static values
thing = Forces.apply(thing, friction);
...
}

Instead, create the force function when we call apply:

const loop() => {
thing = Forces.apply(thing,
Force.velocityForce(0.00001 * thing.smoothness)
);
...
}

Optional

We can also opt to dynamically apply a force or not, based on some state using a ternary operator.

In this example, we assume gravityApplies is a property of the thing. If the value is true, we apply a gravity force, if not a ‘null’ force which does nothing:

Forces.apply(thing,
dragForce,
thing.gravityApplies ? gravityForce : Forces.nullForce,
windForce
);

This technique is used in the basic forces demo to selectively apply forces depending on whether the thing is in ‘air’ or ‘water’