Skip to content

Instantly share code, notes, and snippets.

@fabienjuif
Created August 28, 2018 08:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabienjuif/a7d9fc3e34e23f6000bcfc185dc0e341 to your computer and use it in GitHub Desktop.
Save fabienjuif/a7d9fc3e34e23f6000bcfc185dc0e341 to your computer and use it in GitHub Desktop.
matter-js / dirty fix for CCD and velocity that doesn't scale with delta ticks
const update = (entity, delta) => {
const { body } = entity
// move using `setPosition` and scale it with time since `setVelocity` doesn't scale with time (yet ?)
Body.setPosition(
body,
Vector.add(
body.position,
Vector.mult(
{ x: 1, y: 0 },
0.5 * delta,
),
),
)
}
export default {
update,
}
const fakedFrequence = (1000 / 60) // this is what we inject into physical engine (matter)
const realFrequence = (1000 / 120) // but in real life we target this frequence, here it means we run twice the engine per frame
let tickToCatchUp = 0 // number of milliseconds to catch up in cases where delta / frequence is not a round number
const loop = (delta) => {
// engine
// - run the engine several times, so we have the feeling the game is fast
// - also, this avoid collision detecting issue since CCD is not implemented yet in matter-js
const ticks = (delta / realFrequence)
let ticksInt = Math.floor(ticks)
tickToCatchUp += (ticks - ticksInt)
if (tickToCatchUp >= 1) {
tickToCatchUp -= 1
ticksInt += 1
}
for (let i = 0; i < ticksInt; i += 1) {
// entities
// - remove them is not alive anymore
bodies.forEach((body) => {
const { entity } = body
Body.setAngle(body, 0) // FIXME: look at friction, etc on bodies to avoid them to turn instead of doing this
if (!Entity.update(entity, realFrequence)) World.remove(engine.world, body)
})
// matter-js
Engine.update(engine, fakedFrequence) // fixed frequence
}
}
@osfa
Copy link

osfa commented Oct 4, 2018

Hi thanks for this, any chance you could elaborate on how delta is computed and how the loop func is hooked into? thanks again

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment