Basic implementations

This commit is contained in:
Mal
2020-01-22 22:50:45 +01:00
parent 893c226fe4
commit fb762d1778
17 changed files with 424 additions and 13 deletions

View File

@@ -0,0 +1,60 @@
import RetroSprite from "./RetroSprite.js";
export default class RetroAnimation extends RetroSprite
{
constructor(image, frames, scale = 1, fps = 6)
{
super(image, scale);
this.frames = frames;
this.fps = fps;
this.frameDuration = 1000 / this.fps;
this.currentFrame = 0;
this.lastUpdate = undefined;
this.frameWidth = this.canvas.width / this.frames;
this.isPlaying = false;
}
getWidth() {
return this.frameWidth;
}
setFootPosition(x, y) {
this.position.x = x - this.frameWidth * 0.5;
this.position.y = y - this.canvas.height;
}
play(timestamp)
{
this.isPlaying = true;
if (this.lastUpdate === undefined) {
this.lastUpdate = timestamp;
}
if (timestamp - this.lastUpdate >= this.frameDuration) {
this.currentFrame = (this.currentFrame + 1) % this.frames;
this.lastUpdate = timestamp;
}
}
draw(context)
{
if (!this.isPlaying) {
this.currentFrame = 0;
}
context.drawImage(
this.canvas,
this.frameWidth * this.currentFrame,
0,
this.frameWidth,
this.canvas.height,
this.position.x,
this.position.y,
this.frameWidth,
this.canvas.height
);
this.isPlaying = false;
}
}

View File

@@ -1,10 +1,12 @@
import GeometryPoint from "../geometry/GeometryPoint.js";
import GeometryRect from "../geometry/GeometryRect.js";
export default class RetroSprite
{
constructor(image, scale = 1)
{
this.image = image;
this.image = new Image();
this.image.src = image;
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.position = new GeometryPoint();
@@ -13,6 +15,37 @@ export default class RetroSprite
this.render();
}
/**
* Returns the position of the sprite's center
*
* @returns {GeometryPoint}
*/
getCenter()
{
this.getRect().getCenter();
}
setFootPosition(x, y)
{
this.position.x = x - this.canvas.width * 0.5;
this.position.y = y - this.canvas.height;
}
getRect()
{
return new GeometryRect(this.position.x, this.position.y, this.canvas.width, this.canvas.height);
}
getWidth()
{
return this.canvas.width;
}
getHeight()
{
return this.canvas.height;
}
draw(context)
{
context.drawImage(this.canvas, this.position.x, this.position.y);
@@ -20,7 +53,7 @@ export default class RetroSprite
hasRectCollisionWith(sprite)
{
return this.getRect().getRectIntersection(sprite.getRect()) !== null;
}
hasCollisionWith(sprite)
@@ -31,6 +64,9 @@ export default class RetroSprite
render()
{
let canvasTemp = document.createElement('canvas');
canvasTemp.width = this.image.width * this.scale;
canvasTemp.height = this.image.height * this.scale;
let contextTemp = canvasTemp.getContext('2d');
contextTemp.drawImage(this.image, 0, 0);