MatterJS-with-Phaser (loss of energy)
See: https://github.com/liabru/matter-js/issues/256
by Jeroen Heijmans
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.55.2/phaser.min.js"></script>
<div id="phaser-example" />
JavaScript
class Example extends Phaser.Scene
{
maxY = 0;
minY = 400;
lastY = 0;
duration = 0;
prevDuration = 0;
create () {
this.logo = this.matter.add.rectangle(400, 100, 40, 10, {
inertia: Infinity,
restitution: 1,
friction: 0,
frictionAir: 0,
frictionStatic: 0,
slop: 0.5,
});
this.lastY = this.logo.position.y;
this.text = this.add.text(10, 10, '', { font: '16px Courier', fill: '#00ff00' });
}
update (time, delta) {
this.text.setText([
'this.duration: ' + this.prevDuration,
'last y: ' + this.lastY,
'min y: ' + this.minY,
'max y: ' + this.maxY
]);
if (Phaser.Math.Fuzzy.LessThan(this.logo.velocity.y, 0, 0.1)) {
this.direction = 'up';
} else {
this.direction = 'down';
}
console.log(this.logo);
var y = this.logo.bounds.min.y;
if (this.prevDirection !== this.direction && this.prevDirection === 'up') {
var marker = this.add.line(400, y, 0, y, 500, y, 0x55ff0000);
this.lastY = y;
this.prevDuration = this.duration;
this.duration = 0;
}
this.prevDirection = this.direction;
this.duration += delta;
this.minY = Math.min(this.minY, y);
this.maxY = Math.max(this.minY, this.maxY, this.lastY);
}
}
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'phaser-example',
physics: {
default: 'matter',
matter: {
debug: true,
setBounds: true,
restingThresh: 0.001,
positionIterations: 30,
velocityIterations: 25,
constraintIterations: 18,
runner: {
isFixed: true,
fps: 240,
correction: 10,
},
gravity: { y: 2 }
...