html
\u003c!DOCTYPE html\u003e
\u003chtml\u003e
\u003chead\u003e
\u003ctitle\u003eSimple 2D Platformer\u003c/title\u003e
\u003cstyle\u003e
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
canvas {
display: block;
margin: 0 auto;
width: 100%;
height: 100%;
}
\u003c/style\u003e
\u003c/head\u003e
\u003cbody\u003e
\u003ccanvas id=\"canvas\" width=\"640\" height=\"480\"\u003e\u003c/canvas\u003e
\u003cscript\u003e
// Create the canvas and context
var canvas = document.getElementById(\"canvas\");
var ctx = canvas.getContext(\"2d\");
// Create the player
var player = {
x: 100,
y: 100,
width: 50,
height: 50,
speed: 5
};
// Create the platforms
var platforms = [
{
x: 100,
y: 200,
width: 200,
height: 50
},
{
x: 300,
y: 300,
width: 100,
height: 50
},
{
x: 500,
y: 400,
width: 50,
height: 50
}
];
// Update the game state
function update() {
// Handle player movement
if (keys[37]) { // Left arrow key
player.x -= player.speed;
}
if (keys[39]) { // Right arrow key
player.x += player.speed;
}
if (keys[38]) { // Up arrow key
player.y -= player.speed;
}
if (keys[40]) { // Down arrow key
player.y += player.speed;
}
// Handle player collision with platforms
for (var i = 0; i \u003c platforms.length; i++) {
var platform = platforms[i];
if (player.x + player.width \u003e platform.x &&
player.x \u003c platform.x + platform.width &&
player.y + player.height \u003e platform.y &&
player.y \u003c platform.y + platform.height) {
// The player is colliding with the platform
if (player.y \u003c platform.y) {
// The player is above the platform
player.y = platform.y - player.height;
} else if (player.y \u003e platform.y + platform.height) {
// The player is below the platform
player.y = platform.y + platform.height;
} else if (player.x \u003c platform.x) {
// The player is to the left of the platform
player.x = platform.x - player.width;
} else if (player.x \u003e platform.x + platform.width) {
// The player is to the right of the platform
player.x = platform.x + platform.width;
}
}
}
}
// Draw the game state
function draw() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the player
ctx.fillStyle = \"#0000FF\";
ctx.fillRect(player.x, player.y, player.width, player.height);
// Draw the platforms
ctx.fillStyle = \"#00FF00\";
for (var i = 0; i \u003c platforms.length; i++) {
var platform = platforms[i];
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
}
}
// The main game loop
function gameLoop() {
update();
draw();
// Request the next animation frame
requestAnimationFrame(gameLoop);
}
// Start the game loop
gameLoop();
\u003c/script\u003e
\u003c/body\u003e
\u003c/html\u003e