Created
August 28, 2018 08:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi thanks for this, any chance you could elaborate on how delta is computed and how the loop func is hooked into? thanks again