我在Javascript中制作一个非常简单的游戏。游戏需要通过不同的键同时移动两个对象。我曾尝试过其他方法一次使用两个密钥代码,但它们没有用。他们还需要继续前进,而不仅仅是移动一次。有什么帮助吗?
答案 0 :(得分:1)
在此处查看我的演示:https://jsfiddle.net/mulperi/oh7n3Lx9/ 它展示了如何制作两个基于类的玩家并同时单独控制它们。
我希望这可以帮到你!
以下是完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>World's BEstest Game</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1 style="font-family: Comic Sans MS; color: hotpink; text-shadow: 2px 2px 2px pink">Player Movement 2.0</h1>
<p>Class based player objects and keyboard controls</p>
<p>Use the arrow and WASD keys to move your balls</p>
<canvas id="canvas" style="border:1px solid black; border-radius: 5px;">
</canvas>
<script>
const c = document.getElementById("canvas");
const ctx = c.getContext("2d");
let settings = {
width: 100,
height: 100,
speed: 1
};
c.width = settings.width;
c.height = settings.height;
/*
Object holding boolean values for every keypress
*/
let keyPresses = {};
function listenKeyboard() {
document.addEventListener("keyup", keyUp);
document.addEventListener("keydown", keyDown);
};
const keyUp = e => {
keyPresses[e.key] = false;
};
const keyDown = e => {
// console.log(e.key)
keyPresses[e.key] = true;
};
class Player {
constructor(x, y, color, left, right, up, down, radius) {
this.x = x;
this.y = y;
this.color = color;
this.left = left;
this.right = right;
this.up = up;
this.down = down;
this.radius = radius;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
update() {
if (keyPresses[this.left]) {
this.x -= settings.speed;
}
if (keyPresses[this.right]) {
this.x += settings.speed;
}
if (keyPresses[this.up]) {
this.y -= settings.speed;
}
if (keyPresses[this.down]) {
this.y += settings.speed;
}
// Screen bounds
if (this.x < 0 + this.radius) this.x = 0 + this.radius;
if (this.y < 0 + this.radius) this.y = 0 + this.radius;
if (this.x > settings.width - this.radius) this.x = settings.width - this.radius;
if (this.y > settings.height - this.radius) this.y = settings.width - this.radius;
}
}
/*
Creating the player objects
*/
let p1 = new Player(25, 25, "red", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", 10);
let p2 = new Player(75, 75, "black", "a", "d", "w", "s", 5);
function draw() {
ctx.clearRect(0, 0, settings.width, settings.height);
p1.draw();
p2.draw();
};
function update() {
draw();
listenKeyboard();
p1.update();
p2.update();
requestAnimationFrame(update);
};
requestAnimationFrame(update);
</script>
</body>
</html>