Phaser 3 - Matter and Movement
Moving sprite by fixed time step of matter
by ragesoft
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.54.0/phaser.min.js"></script>
<div id="game">
</div>
JavaScript
var maxFrames = 70; // some config for how many indiviual frames we got
class Demo extends Phaser.Scene {
constructor() {
super({
key: 'examples'
})
}
preload() {
this.load.image( "ground", 'https://labs.phaser.io/assets/textures/water.png');
this.load.image( "ship", 'https://labs.phaser.io/assets/games/asteroids/ship.png');
}
create(){
// fix timestep for matter, better for appling forces, else the ship speed somteimtes "drops / jumps" to higher values
this.physicsTimeout = 0;
this.matterTimeStep = 16.66; // 60 FPS = 16.66, 30 FPS = 33.33
this.bg = this.add.tileSprite( 0, 0, this.game.config.width, this.game.config.height, "ground")
.setOrigin( 0 )
.setScrollFactor( 0 );
this.ship = this.matter.add.sprite( this.game.config.width / 2, this.game.config.height / 2, "ship" )
.setBody( {
type: 'circle',
radius: 10,
},{
frictionAir: 0.1
})
.setMass( 100 );
this.cameras.main.startFollow( this.ship );
this.debugText = this.add.text( 10, 10, "Debug")
.setScrollFactor( 0 );
this.input.on( "pointermove", this.updateShip, this );
this.shipSpeed = 0;
this.matter.world.update30Hz();
}
update(time, delta){
// update underground position
this.bg.setTilePosition( this.cameras.main.worldView.x, this.cameras.main.worldView.y );
// moving te ship with current speed set;
this.ship.thrust( this.shipSpeed );
// update physics by fixed timestep
this.physicsTimeout += delta;
while(this.physicsTimeout >= this.matterTimeStep) {
this.physicsTimeout -= this.matterTimeStep;
this.matter.world.step(this.matterTimeStep);
}
// update Debug-Text
let txt = "World: " +
this.cameras.main.worldView.x.toFixed() + "/" + this.cameras.main.worldView.y.toFixed() +
"\nShip: " +
this.ship.x.toFixed() +...