Skip to content

Instantly share code, notes, and snippets.

@tobspr
Created April 9, 2018 19:46
Show Gist options
  • Save tobspr/2338147517c3430c8343d1ef1db35cbe to your computer and use it in GitHub Desktop.
Save tobspr/2338147517c3430c8343d1ef1db35cbe to your computer and use it in GitHub Desktop.
import Phaser from "phaser-ce"
// Super fast sprite. No rotation, no scale, no tint - only position and alpha
// Can only be used with the super fast renderer
export class FastParticleSprite {
constructor(texture) {
this._texture = texture.baseTexture
// Sanity check
// if (!this._texture) {
// throw new Error("invalid texture")
// }
this.alive = true
this.exists = true
this.position = new Phaser.Point(0, 0)
this.alpha = 1.0
}
// Required for supporting animations
get x() { return this.position.x }
set x(value) { this.position.x = value }
get y() { return this.position.y }
set y(value) { this.position.y = value }
kill() {
this.alive = false
this.exists = false
}
revive() {
this.alive = true
this.exists = true
}
destroy() {
// todo
this._texture = null
this.exists = false
this.alive = false
}
}
// Super fast renderer
export class FastParticleContainer {
constructor(phaser, name) {
this.name = name
this.children = []
this.phaser = phaser
}
add(particle) {
// Sanity check
// if (!(particle instanceof FastParticleSprite)) {
// throw new Error("not supported")
// }
this.children.push(particle)
}
preUpdate() {
// nothing
}
destroy() {
this.children.forEach((child) => child.destroy())
this.children = []
}
update() {
// nothing
}
postUpdate() {
// nothing
}
updateTransform() {
// nothing
}
/* eslint-disable max-statements */
_renderCanvas(renderer) {
const len = this.children.length
// No children
if (len < 1) {
return
}
// Get information from first children
const tex = this.children[0]._texture
// Get width and height
const width = tex.width
const height = tex.height
const image = tex.source
// Compute camera offset
const camera = this.phaser.camera
const offsetX = -camera.position.x - Math.floor(width / 2)
const offsetY = -camera.position.y - Math.floor(height / 2)
// Compute culling information
const minX = -width
const minY = -height
const maxX = camera.width + width
const maxY = camera.height + height
// Get context and clear transform
const context = renderer.context
context.save()
context.setTransform(1, 0, 0, 1, 0, 0)
// Render all children
for (let i = 0; i < len; i += 1) {
const child = this.children[i]
if (child.alive && child.alpha > 0.0039) { // 1 / 255.0
const x = child.position.x + offsetX
const y = child.position.y + offsetY
// Culling
if (x > minX && x < maxX && y > minY && y < maxY) {
context.globalAlpha = child.alpha
context.drawImage(image,
Math.round(child.position.x + offsetX),
Math.round(child.position.y + offsetY)
)
}
}
}
// Restore initial transform
context.restore()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment