我正在做一个几何短跑游戏。我现在尝试旋转我不断绘制的矩形。我需要让它在基本跳跃时能跳180度。我所尝试的一切只是打破了一切,画布是5倍小。我该怎么做?
下面的代码来自不同的文件,顺序可能不对
//player class
class Player {
constructor() {
this.position = {
x: 280,
y: 100,
}
this.velocity = {
x: 0,
y: 0,
}
this.width = 50
this.height = 50
this.sides = {
bottom: this.position.y + this.height,
left: this.position.x,
right: this.position.x + this.width,
top: this.position.y,
}
this.gravity = 1
}
draw() {
c.fillStyle = 'red'
c.fillRect(this.position.x, this.position.y, this.width, this.height)
}
update() {
this.position.x += this.velocity.x
this.position.y += this.velocity.y
this.sides.bottom = this.position.y + this.height
if (this.sides.bottom + this.velocity.y < canvas.height - this.height) {
this.velocity.y += 1
} else this.velocity.y = 0
}
}
//index file
const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')
canvas.width = 1024
canvas.height = 576
const background = {
position: {
x: 0,
y: 0,
}
}
const player = new Player()
const keys = {
w: {
pressed: false,
},
}
function animate() {
window.requestAnimationFrame(animate)
c.clearRect(background.position.x, background.position.y, canvas.width, canvas.height)
player.velocity.x = 0
player.draw()
player.update()
}
animate()
//events file
window.addEventListener('keydown', (event) => {
switch (event.key) {
case 'w':
if (player.velocity.y === 0 || jumps > 0) {
player.velocity.y = -17.5;
rotate = true;
angle += Math.PI; // 180 degrees
}
}
});
function update() {
player.velocity.y += gravityAcceleration;
player.position.x += player.velocity.x;
player.position.y += player.velocity.y;
if (player.position.y >= canvas.height - player.height) {
player.position.y = canvas.height - player.height;
player.velocity.y = 0;
}
}
body {
background: black;
}
canvas {
background-color: white;
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<head></head>
<body>
<canvas></canvas>
</body>
<script src="js/classes/Player.js"></script>
<script src="js/classes/events.js"></script>
<script src="index.js"></script>
</html>
1条答案
按热度按时间q9yhzks01#
每次按下
w
键,player.jumping
将被设置为true。在update()
函数中,它检查player.jumping
是否为true,并递增player.rotation
。draw()
函数将绘制按player.rotation
的值旋转的播放器。旋转代码来自Rotate square on its axis in HTML5 Canvas?。希望这对你有帮助:)