Суда не отображают игру на холсте - PullRequest
1 голос
/ 07 мая 2020

Я пытаюсь разработать простую игру Canvas, но сейчас я застрял в том, чтобы заставить врагов отображать себя.

Вот код, который я использую:

<html lang="en-us">
<head>
<meta http-equiv="content-type"  content="text/html" charset="utf-8">
<title>Cyber Space War</title>
</head>

<body style="margin:10px">

<canvas id="canvas"  style="background:#111;"></canvas>


<script type="text/javascript">


//   SETUP INICIAL
     var canvas = document.getElementById('canvas'),
         ctx = canvas.getContext('2d');
     var innerWidth = 360,
         innerHeight = 620;
         canvas.width = innerWidth;
         canvas.height = innerHeight;


// VARIAVEIS
   var score = 0,
   lastTime = 0;

//   TECLAS DE MOVIMENTAÇÃO
window.onkeydown = pressionaTecla;
function pressionaTecla(tecla){
    if(tecla.keyCode == 38)  {
          player.y = player.y - 10;
    }
    if(tecla.keyCode == 40)  {
          player.y = player.y + 10;
    }
    if(tecla.keyCode == 39)  {
          player.x = player.x + 10;
    }
    if(tecla.keyCode == 37)  {
          player.x = player.x - 10;
    }

}
//   PERSONALIZAÇÃO DO PLAYER
    var player = { },
        player_width = 100,
        player_height = 105,
        player_img = new Image();
        player_img.src = 'images/spaceship.png';

//   OBJETO DO PLAYER
    player = {
        width : player_width,
        height: player_height,
        x : innerWidth/2 - player_width/2,   // centralizar
        y: innerHeight - (player_height+10),  //deixar em baixo
        power : 10,
        draw: function(){


          // FUNÇÃO QUE BLOQUEIA O OBJETO PLAYER SAIR DO CANVAS


          if(this.x <= 0 ){
            this.x = 0;
          }else if (this.x >= (innerWidth - this.width)) {
            this.x = (innerWidth - this.width);
          }

          if(this.y <= 0 ){
            this.y = 0;
          }else if (this.y >= (innerHeight - this.height)) {
            this.y = (innerHeight - this.height);
          }









          ctx.drawImage(player_img, this.x, this.y, this.width, this.height);
        }



   };


// FUNDO DE GALAXIA     *codigo fonte do fundo retirado do site codepen.io     https://codepen.io/LeonGr/pen/fdCsI
   var stars = [], // Array that contains the stars
    FPS = 60, // Frames per second
    x = canvas.width; // Number of stars


    for (var i = 0; i < x; i++) {
  stars.push({
    x: Math.random() * canvas.width,
    y: Math.random() * canvas.height,
    radius: Math.random(),
    vx: Math.floor(Math.random() * 10) - 5,
    vy: Math.floor(Math.random() * 10) - 5
  });
}
function updatefundo() {
  for (var i = 0, x = stars.length; i < x; i++) {
    var s = stars[i];

    s.x += s.vx / FPS;
    s.y += s.vy / FPS;

    if (s.x < 0 || s.x > canvas.width) s.x = -s.x;
    if (s.y < 0 || s.y > canvas.height) s.y = -s.y;
  }
}
function drawfundo() {
  ctx.clearRect(0,0,canvas.width,canvas.height);

  ctx.globalCompositeOperation = "lighter";

  for (var i = 0, x = stars.length; i < x; i++) {
    var s = stars[i];

    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.arc(s.x, s.y, s.radius, 0, 2 * Math.PI);
    ctx.fill();
  }
}




 //  PERSONALIZAÇÃO DO INIMIGO

  var enemyArray = [],
      enemyIndex = 0,
      enemy_width = 35,
      enemy_height = 43,
      enemy_timer = 1000,
      enemy_img = new Image ();
      enemy_img.src = 'images/spaceship.png';

 // OBJETO DO INIMIGO

  function enemy (x, y, dx, dy, enemy_img, enemy_width, enemy_height, rotation){
            this.x = x;
            this.y = y;
            this.dx = dx;
            this.dy = dy;
            this.img = enemy_img;
            this.width = enemy_width;
            this.height = enemy_height;
            this.rotation = rotation;
            enemyIndex++;
            enemyArray[enemyIndex] = this;
            this.id = enemyIndex;

            ctx.drawImage(this.img, this.x, this.y, this.width, this.height);



            this.update = function(){
              this.y+= this.dy;
              this.x+= this.dx;


              this.draw();

            }


            this.delete = function(){
              delete enemyArray[this.id];
            }
            this.draw = function(){
              ctx.drawImage(this.img, this.x, this.y, this.width, this.height);

            }




}



// FUNÇÃO DE CRIAR INIMIGOS


  function create_enemy(){
      var x = Math.random() * (innerWidth - enemy_width);
      var y = -enemy_height;
      var dx = 3;
      var dy = 3;
      var rotation = Math.random();

      new enemy (x, y, dx, dy, enemy_img, enemy_width, enemy_height, rotation);




  }






//  LOOPING DA ANIMAÇAO  (MAINFRAME DO GAME)
  function gameLoop(currentTime){
    requestAnimationFrame(gameLoop);
    ctx.clearRect (0,0,  canvas.width, canvas.height);



    drawfundo();
    updatefundo();

    // SCORE
    ctx.font = '17px arial';
    ctx.fillStyle = '#fff';
    ctx.fillText('PONTOS: '+score , 15, 30);

    // ENERGIA
    ctx.font = '17px arial';
    ctx.fillStyle = '#fff';
    ctx.fillText('ENERGIA '+player.power , innerWidth-110, 30);



    // JOGADOR
    player.draw();


    if(currentTime >= lastTime + enemy_timer){
      lastTime = currentTime;
      create_enemy();
    }
    create_enemy();




  }
    gameLoop();







</script>

работает нормально, за исключением того, что враги не отображаются.

Папка с изображениями уже проверена, и все настроено так, как я ввел в код. Линии врагов: "// PERSONALIZAÇÃO DO INIMI GO" "// OBJETO DO INIMI GO"

1 Ответ

0 голосов
/ 07 мая 2020

Вы рисуете врага за пределы холста. Просто замените var y = -enemy_height на var y = enemy_height:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const innerWidth = canvas.width = window.innerWidth;
const innerHeight = canvas.height = window.innerHeight;


// VARIAVEIS:

let score = 0;
let lastTime = 0;

// TECLAS DE MOVIMENTAÇÃO:

window.onkeydown = (e) => {
  e.preventDefault();
  
  if (e.keyCode == 38) player.y = player.y - 10;
  if (e.keyCode == 40) player.y = player.y + 10;
  if (e.keyCode == 39) player.x = player.x + 10;
  if (e.keyCode == 37) player.x = player.x - 10;
};


// PERSONALIZAÇÃO DO PLAYER:

var player = { },
player_width = 100,
player_height = 105,
player_img = new Image();
player_img.src = 'https://i.stack.imgur.com/L5XWd.png';


// OBJETO DO PLAYER:

player = {
  width : player_width,
  height: player_height,
  x : innerWidth / 2 - player_width / 2, // centralizar
  y: innerHeight - (player_height + 10), //deixar em baixo
  power : 10,
  draw: function() {
    // FUNÇÃO QUE BLOQUEIA O OBJETO PLAYER SAIR DO CANVAS
    
    if(this.x <= 0 ){
      this.x = 0;
    } else if (this.x >= (innerWidth - this.width)) {
      this.x = (innerWidth - this.width);
    }
    
    if(this.y <= 0 ){
      this.y = 0;
    } else if (this.y >= (innerHeight - this.height)) {
      this.y = (innerHeight - this.height);
    }
      
    ctx.drawImage(player_img, this.x, this.y, this.width, this.height);
  }
};


// FUNDO DE GALAXIA (https://codepen.io/LeonGr/pen/fdCsI):

var stars = [], // Array that contains the stars
  FPS = 60, // Frames per second
  x = canvas.width; // Number of stars

for (var i = 0; i < x; i++) {
  stars.push({
    x: Math.random() * canvas.width,
    y: Math.random() * canvas.height,
    radius: Math.random(),
    vx: Math.floor(Math.random() * 10) - 5,
    vy: Math.floor(Math.random() * 10) - 5
  });
}

function updatefundo() {
  for (var i = 0, x = stars.length; i < x; i++) {
    var s = stars[i];
    
    s.x += s.vx / FPS;
    s.y += s.vy / FPS;
    
    if (s.x < 0 || s.x > canvas.width) s.x = -s.x;
    if (s.y < 0 || s.y > canvas.height) s.y = -s.y;
  }
}

function drawfundo() {
  ctx.clearRect(0,0,canvas.width,canvas.height);
  
  ctx.globalCompositeOperation = "lighter";
  
  for (var i = 0, x = stars.length; i < x; i++) {
    var s = stars[i];
    
    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.arc(s.x, s.y, s.radius, 0, 2 * Math.PI);
    ctx.fill();
  }
}


// PERSONALIZAÇÃO DO INIMIGO:

var enemyArray = [],
enemyIndex = 0,
enemy_width = 35,
enemy_height = 43,
enemy_timer = 1000,
enemy_img = new Image();
enemy_img.src = 'https://i.stack.imgur.com/SnOAO.png';


// OBJETO DO INIMIGO:

function enemy (x, y, dx, dy, enemy_img, enemy_width, enemy_height, rotation){
  this.x = x;
  this.y = y;
  this.dx = dx;
  this.dy = dy;
  this.img = enemy_img;
  this.width = enemy_width;
  this.height = enemy_height;
  this.rotation = rotation;
  enemyIndex++;
  enemyArray[enemyIndex] = this;
  this.id = enemyIndex;
  
  ctx.drawImage(this.img, this.x, this.y, this.width, this.height);
  
  this.update = function(){
    this.y+= this.dy;
    this.x+= this.dx;
    
    this.draw();
  }
  
  this.delete = function() {
    delete enemyArray[this.id];
  }
  
  this.draw = function() {
    ctx.drawImage(this.img, this.x, this.y, this.width, this.height);
  }
}


// FUNÇÃO DE CRIAR INIMIGOS:

function create_enemy(){
  var x = Math.random() * (innerWidth - enemy_width);
  var y = enemy_height;
  var dx = 3;
  var dy = 3;
  var rotation = Math.random();
  
  new enemy (x, y, dx, dy, enemy_img, enemy_width, enemy_height, rotation);
}

// LOOPING DA ANIMAÇAO (MAINFRAME DO GAME):

function gameLoop(currentTime){
  ctx.clearRect (0,0,  canvas.width, canvas.height);

  drawfundo();
  updatefundo();
  
  // SCORE
  ctx.font = '17px arial';
  ctx.fillStyle = '#fff';
  ctx.fillText('PONTOS: '+score , 15, 30);
  
  // ENERGIA
  ctx.font = '17px arial';
  ctx.fillStyle = '#fff';
  ctx.fillText('ENERGIA '+player.power , innerWidth-110, 30);

  // JOGADOR
  player.draw();
    
  if(currentTime >= lastTime + enemy_timer){
    lastTime = currentTime;
    create_enemy();
  }
  
  create_enemy();
  
  requestAnimationFrame(gameLoop);

}

requestAnimationFrame(gameLoop);
body {
  margin: 0;
  height: 100vh;
}

#canvas {
  width: 100%;
  height: 100%;
}
<canvas id="canvas"  style="background:#111;"></canvas>

Используемые изображения:

Враг:

Enemy spaceship

Игрок:

Player spaceshift

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...