mr-crocs-adventures/js/module.js

118 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-01-19 00:45:17 +01:00
import RetroSprite from "./retro/RetroSprite.js";
2020-01-22 22:50:45 +01:00
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();
2020-01-19 00:45:17 +01:00
let image = new Image();
2020-01-22 22:50:45 +01:00
image.src = 'graphics/mr-croc-stand.png';
loader.addImage(image);
let imgAnimation = new Image();
imgAnimation.src = 'graphics/mr-croc-walk-right.png';
loader.addImage(imgAnimation);
let imgAnimationB = new Image();
imgAnimationB.src = 'graphics/mr-croc-walk-left.png';
loader.addImage(imgAnimationB);
let imgBackground = new Image();
imgBackground.src = 'graphics/ground.jpg';
loader.addImage(imgBackground);
window.addEventListener(
'imagesloaded',
() => {
console.log('Loaded');
ground = new RetroSprite('graphics/ground.jpg', 4);
ground.position.y = window.innerHeight - ground.getRect().height;
2020-01-19 00:45:17 +01:00
2020-01-22 22:50:45 +01:00
let canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
2020-01-19 00:45:17 +01:00
2020-01-22 22:50:45 +01:00
context = canvas.getContext('2d');
2020-01-19 00:45:17 +01:00
2020-01-22 22:50:45 +01:00
mrCroc = new MrCroc();
mrCroc.position.x = 100;
mrCroc.position.y = window.innerHeight - ground.getHeight();
ground.draw(context);
2020-01-19 00:45:17 +01:00
2020-01-22 22:50:45 +01:00
window.requestAnimationFrame(MainLoop);
}
);