Platformer
by Raul Bojalil
HTML
<div id="debug">Debug</div>
<canvas width="600" height="1000"></canvas>
JavaScript
var LEVEL_ITEM_OBSTACLE = 0;
var LEVEL_ITEM_POWERUP = 1;
//Html elements
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var $debug = document.getElementById("debug");
//Constants
var initialJumpAcceleration = -15;
var jumpHeldAcceleration = -0.7;
var groundY = 220;
var gravity = 0.09;
var movementSpeed = 0.2;
var maxGravityAcceleration = 15;
var levelScrollPointR = 370;
var levelScrollPointL = 100;
var levelScrollSpeed = 1;
var levelWidth = 600;
var maxJumps = 2;
//State
var player = {
x: 0, y: 0, w: 10, h: 30, jumps: 0, powerups: 0, isMovingLeft: false, isMovingRight: false,
isJumping: false, wantsToJump: false, isFalling: false, isJumpHeld: false, gravityAcceleration: 0,
rotationTimer: 0,
};
var level= {
scrollX: 0,
items: [
{ x: 100, y: groundY - 60, w: 80, h: 60, type: LEVEL_ITEM_OBSTACLE },
{ x: 300, y: groundY - 70, w: 50, h: 70, type: LEVEL_ITEM_OBSTACLE },
{ x: 400, y: groundY - 30, w: 60, h: 30, type: LEVEL_ITEM_OBSTACLE },
{ x: 700, y: groundY - 30, w: 60, h: 30, type: LEVEL_ITEM_OBSTACLE },
{ x: 800, y: groundY - 80, w: 60, h: 80, type: LEVEL_ITEM_OBSTACLE },
{ x: 950, y: groundY - 50, w: 60, h: 50, type: LEVEL_ITEM_OBSTACLE },
{ x: 100, y: 80, w: 20, h: 20, type: LEVEL_ITEM_POWERUP },
{ x: 300, y: 80, w: 20, h: 20, type: LEVEL_ITEM_POWERUP },
{ x: 400, y: 80, w: 20, h: 20, type: LEVEL_ITEM_POWERUP },
],
};
//Event handlers
var onKeyDown = (e) => {
if (e.keyCode == 37) {
player.isMovingLeft = true;
}
if (e.keyCode == 39) {
player.isMovingRight = true;
}
if (e.keyCode == 32)
{
if (!player.isJumpHeld) {
player.wantsToJump = true;
}
player.isJumpHeld = true;
}
e.preventDefault();
return false;
}
var onKeyUp = (e) => {
if (e.keyCode == 37) {
player.isMovingLeft = false;
}
if (e.keyCode == 39) {
player.isMovingRight = false;
}
if (e.keyCode == 32) {
player.isJumpHeld = false;
player.wantsToJump = false;
...