Skip to content

Instantly share code, notes, and snippets.

@potaycat
Last active February 14, 2022 07:00
Show Gist options
  • Save potaycat/2d718c18d022176649046ce110fc9047 to your computer and use it in GitHub Desktop.
Save potaycat/2d718c18d022176649046ce110fc9047 to your computer and use it in GitHub Desktop.
My sprite base class for <canvas> rendering
const debug = 0
export default class Sprite {
constructor(x, y, width, height) {
this.x = x
this.y = y
this.width = width
this.height = height
this.angle = 0 // rad
this.frames = []
this.currentFrame = 0
this.framesToDelay = 0
this._framesDelayed = 0
}
isCollidedW(otherSprite) {
let myleft = this.x,
myright = this.x + this.width,
mytop = this.y,
mybottom = this.y + this.height
let otherleft = otherSprite.x,
otherright = otherSprite.x + otherSprite.width,
othertop = otherSprite.y,
otherbottom = otherSprite.y + otherSprite.height
let isCollided = true
if (mybottom < othertop || mytop > otherbottom || myright < otherleft || myleft > otherright) {
isCollided = false
}
return isCollided
}
setAnim(imgArr, framesToDelay = 5) {
this.frames = imgArr.map(img => {
if (!img instanceof HTMLImageElement) {
console.error("Faulty sprite yo")
return "default"
}
img.width = this.width
img.height = this.height
return img
})
this.currentFrame = 0
this.framesToDelay = framesToDelay
}
onAnimCycleDone() { }
getCurFrame() {
return this.frames[this.currentFrame]
}
shiftFrame() {
if (this.currentFrame + 1 >= this.frames.length) {
this.currentFrame = 0
this.onAnimCycleDone()
} else {
this.currentFrame += 1
}
}
update() {
this._framesDelayed += 1
if (this._framesDelayed > this.framesToDelay) {
this.shiftFrame()
this._framesDelayed = 0
}
}
getSpriteCoord() {
return [this.x, this.y, this.width, this.height]
}
draw(ctx) {
if (this.angle) {
ctx.translate(this.x + this.width / 2, this.y + this.height / 2)
ctx.rotate(this.angle)
ctx.drawImage(this.getCurFrame(), ...this.getSpriteCoord())
ctx.setTransform(1, 0, 0, 1, 0, 0)
} else {
// careful when angle is 0
ctx.drawImage(this.getCurFrame(), ...this.getSpriteCoord())
}
if (debug) {
ctx.globalAlpha = 0.2
ctx.fillStyle = this.status || "red"
ctx.fillRect(this.x, this.y, this.width, this.height)
ctx.fillStyle = "green"
ctx.fillRect(...this.getSpriteCoord())
ctx.globalAlpha = 1.0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment