Javascript Games
- javascript是开发游戏的好帮手。
创建一个index.html文件并将以下代码粘贴到其中然后用浏览器打开即可预览效果。
跳跃游戏示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>2DJumpGame</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<canvas id="GameCanvas"></canvas>
<script>
//const canvas = document.querySelector("canvas");
const canvas = document.getElementById("GameCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const context = canvas.getContext("2d");
const gravity = 2000;
let keyW = false;
let keyA = false;
let keyS = false;
let keyD = false;
function getKey(keyName) {
switch (keyName) {
case "w":
return keyW;
case "a":
return keyA;
case "s":
return keyS;
case "d":
return keyD;
}
return false;
}
class Player {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.velocityY = 0;
this.moveSpeed = 400;
}
draw() {
context.fillStyle = "red";
context.fillRect(this.x, this.y, this.width, this.height);
}
update(deltaTime) {
if (getKey("w")) {
if (player.y + player.height === canvas.height) {
player.velocityY = -1000;
}
}
if (getKey("a")) {
this.x -= this.moveSpeed * deltaTime;
}
if (getKey("d")) {
this.x += this.moveSpeed * deltaTime;
}
this.velocityY += gravity * deltaTime;
this.y += this.velocityY * deltaTime;
if (this.y + this.height > canvas.height) {
this.y = canvas.height - this.height;
this.velocityY = 0;
}
player.draw();
}
}
const player = new Player(100, 100, 100, 100);
let lastTime = 0;
function gameLoop(currentTime) {
const deltaTime = (currentTime - lastTime) / 1000;
lastTime = currentTime;
context.clearRect(0, 0, canvas.width, canvas.height);
player.update(deltaTime);
window.requestAnimationFrame(gameLoop);
}
window.requestAnimationFrame(gameLoop);
window.addEventListener("keydown", (event) => {
switch (event.key) {
case "w":
keyW = true;
break;
case "a":
keyA = true;
break;
case "s":
keyS = true;
break;
case "d":
keyD = true;
break;
}
});
window.addEventListener("keyup", (event) => {
switch (event.key) {
case "w":
keyW = false;
break;
case "a":
keyA = false;
break;
case "s":
keyS = false;
break;
case "d":
keyD = false;
break;
}
});
</script>
</body>
</html>