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

@@ -1,17 +1,117 @@
import RetroSprite from "./retro/RetroSprite.js";
import Key from "./Key.js";
import MrCroc from "./MrCroc.js";
const MEDIA_READY_EVENT = 'mediaready';
const IMAGE_READY_EVENT = 'imgready';
class ImageLoader
{
images = [];
numberImagesLoaded = 0;
update()
{
this.numberImagesLoaded++;
if (this.numberImagesLoaded === this.images.length) {
window.dispatchEvent(new Event('imagesloaded'));
}
}
getCurrentProgress()
{
return this.numberImagesLoaded / this.images.length;
}
addImage(image)
{
image.addEventListener(
'load', () => {
this.update();1
}
);
this.images.push(image);
}
}
function MainLoop(timestamp)
{
if (lastRendered === undefined && lastTimestamp === undefined) {
lastRendered = timestamp;
lastTimestamp = timestamp;
}
let delta = (timestamp - lastTimestamp) / (10 / GAME_SPEED);
if (KeyLeft.isPressed()) {
mrCroc.moveLeft(timestamp, delta);
} else if (KeyRight.isPressed()) {
mrCroc.moveRight(timestamp, delta);
}
if (lastRendered >= FRAME_DURATION) {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
ground.draw(context);
mrCroc.draw(context);
lastRendered = timestamp;
}
lastTimestamp = timestamp;
window.requestAnimationFrame(MainLoop);
}
const FPS = 60;
const FRAME_DURATION = 1000 / FPS;
const GAME_SPEED = 1;
let lastRendered = undefined;
let lastTimestamp = undefined;
let context;
let ground, mrCroc;
let KeyLeft = new Key('ArrowLeft');
let KeyRight = new Key('ArrowRight');
let loader = new ImageLoader();
let image = new Image();
image.src = 'graphics/mario.png';
image.src = 'graphics/mr-croc-stand.png';
loader.addImage(image);
image.onload = function () {
let sprite = new RetroSprite(image, 10);
let canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let imgAnimation = new Image();
imgAnimation.src = 'graphics/mr-croc-walk-right.png';
loader.addImage(imgAnimation);
let context = canvas.getContext('2d');
let imgAnimationB = new Image();
imgAnimationB.src = 'graphics/mr-croc-walk-left.png';
loader.addImage(imgAnimationB);
console.log(context);
let imgBackground = new Image();
imgBackground.src = 'graphics/ground.jpg';
loader.addImage(imgBackground);
sprite.draw(context);
};
window.addEventListener(
'imagesloaded',
() => {
console.log('Loaded');
ground = new RetroSprite('graphics/ground.jpg', 4);
ground.position.y = window.innerHeight - ground.getRect().height;
let canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context = canvas.getContext('2d');
mrCroc = new MrCroc();
mrCroc.position.x = 100;
mrCroc.position.y = window.innerHeight - ground.getHeight();
ground.draw(context);
window.requestAnimationFrame(MainLoop);
}
);