diff --git a/public/assets/img/ship.png b/public/assets/img/ship.png new file mode 100644 index 0000000..b43a2e4 Binary files /dev/null and b/public/assets/img/ship.png differ diff --git a/src/classes/Ship.ts b/src/classes/Ship.ts new file mode 100644 index 0000000..8cbe230 --- /dev/null +++ b/src/classes/Ship.ts @@ -0,0 +1,48 @@ +import Phaser from 'phaser' + +export default class Ship extends Phaser.Physics.Arcade.Sprite { + readonly acceleration = 5 + readonly dragForce = 0.6 + + readonly colliderRadiusRatio = 0.43 + readonly wrapMargin = 10 + + constructor(scene: Phaser.Scene) { + super( + scene, + scene.physics.world.bounds.centerX, + scene.physics.world.bounds.centerY, + 'ship' + ) + + scene.add.existing(this) + scene.physics.add.existing(this) + + scene.input.on('pointermove', (pointer) => { + this.rotation = Phaser.Math.Angle.BetweenPoints(this, pointer) + Math.PI / 2 + }) + + this.setDamping(true) + this.setDrag(this.dragForce) + this.body.setCircle(this.width * this.colliderRadiusRatio) + } + + preUpdate(time, delta) { + super.preUpdate(time, delta) + + const keyUp = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W) + const keyDown = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S) + const keyLeft = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A) + const keyRight = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D) + + const vec = new Phaser.Math.Vector2(0, 0) + + if (keyUp.isDown) vec.y = -this.acceleration + if (keyDown.isDown) vec.y = this.acceleration + if (keyRight.isDown) vec.x = this.acceleration + if (keyLeft.isDown) vec.x = -this.acceleration + + this.body.velocity.add(vec) + this.scene.physics.world.wrap(this, this.wrapMargin) + } +} diff --git a/src/main.ts b/src/main.ts index 56f504c..0269360 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,12 +4,14 @@ import DefaultScene from './scenes/DefaultScene' const config: Phaser.Types.Core.GameConfig = { type: Phaser.AUTO, + width: 800, height: 600, + physics: { default: 'arcade', arcade: { - gravity: { y: 200 } + debug: true } }, scene: [DefaultScene] diff --git a/src/scenes/DefaultScene.ts b/src/scenes/DefaultScene.ts index 2d503d6..76e8ec8 100644 --- a/src/scenes/DefaultScene.ts +++ b/src/scenes/DefaultScene.ts @@ -1,13 +1,17 @@ import Phaser from 'phaser' +import Ship from '../classes/Ship' export default class DefaultScene extends Phaser.Scene { + player?: Ship + constructor() { - super('hello-world') + super('default-scene') } preload() { this.load.image('sky', 'assets/img/nebula10.png') this.load.image('logo', 'assets/img/phaser3-logo.png') + this.load.image('ship', 'assets/img/ship.png') this.load.spritesheet('particles', 'assets/img/boom.png', { frameWidth: 192, frameHeight: 192 }) } @@ -29,5 +33,7 @@ export default class DefaultScene extends Phaser.Scene { logo.setCollideWorldBounds(true) emitter.startFollow(logo) + + this.player = new Ship(this) } }