JSFiddle - React, Tailwind, and code Playground

by Ben Gillbanks

HTML

<canvas id="gameCanvas" width="600" height="400"></canvas>

JavaScript

class Platformer {
			constructor(canvasId, map, tileWidth, tileHeight, heroWidth, heroHeight, gravity) {
				this.canvas = document.getElementById(canvasId);
				this.ctx = this.canvas.getContext('2d');
				this.map = map;
				this.tileWidth = tileWidth;
				this.tileHeight = tileHeight;
				this.mapWidth = map[0].length;
				this.mapHeight = map.length;
				this.heroWidth = heroWidth;
				this.heroHeight = heroHeight;
				this.gravity = gravity;
				this.heroX = 3;
				this.heroY = 2;
				this.heroVy = 0;
                this.heroVx = 0;
				this.heroGrounded = 0;
				this.heroCanJump = 1;
				this.scrollX = 0;
				this.keys = { left: false, right: false, up: false };

				this.setupEventListeners();
				this.gameLoop();
			}

			setupEventListeners() {
				window.addEventListener('keydown', (e) => this.handleKeyDown(e));
				window.addEventListener('keyup', (e) => this.handleKeyUp(e));
			}

			handleKeyDown(e) {
				switch (e.code) {
					case 'ArrowRight':
					case 'KeyD':
						this.keys.right = true;
						break;
					case 'ArrowLeft':
					case 'KeyA':
						this.keys.left = true;
						break;
					case 'ArrowUp':
					case 'KeyW':
                    console.log('jump');
						this.keys.up = true;
						break;
				}
			}

			handleKeyUp(e) {
				switch (e.code) {
					case 'ArrowRight':
					case 'KeyD':
						this.keys.right = false;
						break;
					case 'ArrowLeft':
					case 'KeyA':
						this.keys.left = false;
						break;
					case 'ArrowUp':
					case 'KeyW':
						this.keys.up = false;
						break;
				}
			}

			gameLoop() {
				setInterval(() => {
					this.update();
					this.draw();
				}, 1000 / 60);
			}

			update() {
				this.updateHeroPosition();
				this.handleCollisions();
				this.updateScroll();
			}

			updateHeroPosition() {
				this.heroVy += this.gravity;
				this.heroY += this.heroVy;
                this.heroX += this.heroVx;
                this.heroVx *= 0.75;

/* 				if (this.heroY < 0) {
				    this.heroY = 0;
				   ...