[英]My Javascript code for a flappy bird game isn't displaying the character as it's meant to do
I am new to Javascript and I am trying to create flappy bird in normal Javascript.我是 Javascript 的新手,我正在尝试在正常的 Javascript 中创建飞扬的鸟。 I was following a tutorial and when I got to this point my code wasn't working and wasn't displaying the character (a yellow square) as it is apparently meant to be doing according to the tutorial.
我正在关注一个教程,当我到达这一点时,我的代码无法正常工作并且没有显示字符(黄色方块),因为它显然是按照教程要做的。 I was hoping that someone would be able to help me with my issue, thanks a lot.
我希望有人能够帮助我解决我的问题,非常感谢。
This is my HTML code here:这是我的 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>
This is my Javascript code here:这是我的 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();
}
The size of your canvas is only 320px, but you are trying to draw a square at a position of 400px.您的 canvas 的大小仅为 320 像素,但您尝试在 400 像素的 position 处绘制一个正方形。
Try:尝试:
p = new Player(0, 400)
It works有用
The player is being drawn offscreen: the x
coordinate for player (as well as the y
coordinate) is 400
, while the canvas is only 320
wide.播放器被绘制到屏幕外:播放器的
x
坐标(以及y
坐标)是400
,而 canvas 只有320
宽。 I'd recommend you check the line p = new Player(400, 400)
to ensure the numbers are correct.我建议您检查
p = new Player(400, 400)
行以确保数字正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.