Skip to content

Instantly share code, notes, and snippets.

@ehgoodenough
Created January 24, 2016 07:56
Show Gist options
  • Save ehgoodenough/cae64d635ad508bd0c91 to your computer and use it in GitHub Desktop.
Save ehgoodenough/cae64d635ad508bd0c91 to your computer and use it in GitHub Desktop.
var Pixi = require("pixi.js")
var Afloop = require("afloop")
var Keyb = require("keyb")
var WIDTH = 230, HEIGHT = 130
var renderer = Pixi.autoDetectRenderer(WIDTH, HEIGHT)
renderer.backgroundColor = 0x0F380F
renderer.roundPixels = true
document.getElementById("mount").appendChild(renderer.view)
window.game = new Pixi.Container()
var defenderImage = Pixi.Texture.fromImage(require("./images/defender.png"))
var invaderImage = Pixi.Texture.fromImage(require("./images/invader1.png"))
var projectileImage = Pixi.Texture.fromImage(require("./images/projectile.png"))
class Defender extends Pixi.Sprite {
constructor() {
super(defenderImage)
this.position.x = WIDTH / 2
this.position.y = HEIGHT - 2
this.anchor.x = 0.5
this.anchor.y = 1
this.speed = 20
}
update(delta) {
if(Keyb.isDown("D") || Keyb.isDown("<right>")) {
this.position.x += this.speed * delta
} else if(Keyb.isDown("A") || Keyb.isDown("<left>")) {
this.position.x -= this.speed * delta
}
if(Keyb.isJustDown("<space>")) {
game.addChild(new Projectile(this.position.x))
}
}
}
var defender = new Defender()
game.addChild(defender)
class Invader extends Pixi.Sprite {
constructor(x) {
super(invaderImage)
this.position.x = x
this.anchor.x = 0.5
}
update(delta) {
this.position.y += Math.random() * 10 * delta
}
}
class BossInvader extends Invader {
constructor(x) {
super(WIDTH / 2)
this.scale.x *= 4
this.scale.y *= 4
}
}
for(var x = 0; x < WIDTH; x += 20) {
game.addChild(new Invader(x))
}
class Projectile extends Pixi.Sprite {
constructor(x) {
super(projectileImage)
this.position.x = x
this.position.y = HEIGHT - 10
this.anchor.x = 0.5
this.anchor.y = 0
this.speed = 40
}
update(delta) {
this.position.y -= this.speed * delta
if(this.position.y < -this.height) {
game.removeChild(this)
}
game.children.forEach((child) => {
if(child instanceof Invader) {
if(Math.abs(child.position.y - this.position.y) < this.height
&& Math.abs(child.position.x - this.position.x) < child.width * 0.5) {
game.removeChild(child)
game.removeChild(this)
if(game.children.length == 1) {
if(!game.hasSeenTheBoss) {
game.hasSeenTheBoss = true
game.addChild(new BossInvader())
}
}
}
}
})
}
}
var loop = new Afloop(function(delta) {
game.children.forEach(function(child) {
child.update(delta)
})
renderer.render(game)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment