[英]My Javascript code for a flappy bird game isn't displaying the character as it's meant to do
我是 Javascript 的新手,我正在嘗試在正常的 Javascript 中創建飛揚的鳥。 我正在關注一個教程,當我到達這一點時,我的代碼無法正常工作並且沒有顯示字符(黃色方塊),因為它顯然是按照教程要做的。 我希望有人能夠幫助我解決我的問題,非常感謝。
這是我的 HTML 代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flappy Bird</title>
<style>
canvas {
border: 3px solid #000000;
display: block;
margin: 0 auto;
background-color: lightblue;
}
</style>
</head>
<body>
<canvas id="canvas" width="320" height="480"></canvas>
<script src="game.js"></script>
</body>
</html>
這是我的 Javascript 代碼:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.w = 40;
this.h = 40;
this.ySpeed = 3;
}
show() {
ctx.fillStyle = "yellow";
ctx.fillRect(this.x, this.y, this.w, this.h);
}
update() {
this.y += this.ySpeed;
this.ySpeed += gravity;
}
}
var p;
var gravity = 0.1;
window.onload = function () {
start();
setInterval(update, 10);
};
function start() {
p = new Player(400, 400);
}
function update() {
canvas.width = canvas.width;
//player
p.show();
p.update();
}
您的 canvas 的大小僅為 320 像素,但您嘗試在 400 像素的 position 處繪制一個正方形。
嘗試:
p = new Player(0, 400)
有用
播放器被繪制到屏幕外:播放器的x
坐標(以及y
坐標)是400
,而 canvas 只有320
寬。 我建議您檢查p = new Player(400, 400)
行以確保數字正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.