FINALLY you can shoot asteroid!.. and dead.

This commit is contained in:
KGrzeg 2021-10-16 02:51:17 +02:00
parent 2db1cda5bb
commit 65b99a20d8
3 changed files with 49 additions and 6 deletions

View file

@ -1,8 +1,11 @@
import Phaser from 'phaser'
import Bullet from '../classes/Bullet'
export default class Asteroid extends Phaser.Physics.Arcade.Sprite {
static unbornAge = 1000 // asteroid can't kill player
// if younger than 1000ms
// asteroid can't kill player
// if younger than unbornAge in ms
static unbornAge = 1000
readonly wrapMargin = 30
age = 0
@ -30,11 +33,20 @@ export default class Asteroid extends Phaser.Physics.Arcade.Sprite {
preUpdate(time: number, delta: number) {
super.preUpdate(time, delta)
this.scene.physics.world.wrap(this, this.scale * this.wrapMargin)
this.age += delta
}
gotHit(me, bullet) {
if (!(bullet instanceof Bullet)) return
if (bullet.active == false) return
me.destroy() // TODO: use objects pool
bullet.setActive(false)
bullet.setVisible(false)
}
private setRandomShade() {
const color = new Phaser.Display.Color()
color.randomGray(0xa0) //the darkest possible dye is 0xa0a0a0

View file

@ -1,6 +1,7 @@
import Phaser from 'phaser'
import Bullets from './Bullets'
import Thruster from './Thruster'
import Asteroid from './Asteroid'
export default class Ship extends Phaser.Physics.Arcade.Sprite {
readonly acceleration = 5
@ -66,4 +67,13 @@ export default class Ship extends Phaser.Physics.Arcade.Sprite {
this.scene.physics.world.wrap(this, this.wrapMargin)
this.thruster.update(time, delta)
}
gotHit(_, asteroid) {
if (!(asteroid instanceof Asteroid)) return
if (asteroid.age > Asteroid.unbornAge) {
console.log("%cU ded", "color:red")
this.scene.cameras.main.shake(100, 0.02)
}
}
}

View file

@ -3,10 +3,11 @@ import Ship from '../classes/Ship'
import Asteroid from '../classes/Asteroid'
export default class DefaultScene extends Phaser.Scene {
readonly maxGameObjects = 100
readonly maxAsteroids = 70
player?: Ship
rotFrames?: Phaser.Types.Animations.AnimationFrame[]
asteroids?: Phaser.GameObjects.Group
constructor() {
super('default-scene')
@ -22,6 +23,8 @@ export default class DefaultScene extends Phaser.Scene {
}
create() {
this.asteroids = this.add.group()
Asteroid.createAnimations(this)
this.add.image(400, 300, 'sky')
@ -32,10 +35,28 @@ export default class DefaultScene extends Phaser.Scene {
callbackScope: this,
repeat: -1
});
this.hookupCollisions()
}
spawnAsteroids() {
if (this.children.length < this.maxGameObjects)
new Asteroid(this)
if (this.asteroids!.getLength() < this.maxAsteroids)
this.asteroids!.add(new Asteroid(this))
}
hookupCollisions() {
// player - asteroids
this.physics.add.overlap(
this.player!, this.asteroids!, // colliders
this.player!.gotHit, // callback
undefined, // callback filter
this.player // 'this' for callback
)
// bullets - asteroids
this.physics.add.overlap(
this.asteroids!, this.player!.bullets,
Asteroid.prototype.gotHit
)
}
}