简体   繁体   中英

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. 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:

<!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:

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.

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. I'd recommend you check the line p = new Player(400, 400) to ensure the numbers are correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM