以不同的速度生成随机图像

spawn random images with different speed

本文关键字:随机 图像 速度      更新时间:2024-04-05

我有一个太空射击游戏,其中一个平面从屏幕顶部下来,这个平面被称为enemy.png,但现在我想添加更多的enemys。但是我不知道从哪里开始。我想添加另一个敌人,称为enemy1.png。这个敌人也需要有不同的速度,然后enemy.png

希望你们能帮忙。

这是敌人的代码

//enemies
var enemy;
var enemyTotal = 5;
var enemies = [enemy1,enemy2];
var enemy_x = 50;
var enemy_y = -45;
var enemy_w = 50;
var enemy_h = 50;
var speed = 3;




//Build enemy array of x/y coordinate, width, height, and speed
for (var i = 0; i < enemyTotal; i++) {
enemies.push([enemy_x, enemy_y, enemy_w, enemy_h, speed]);
  enemy_x += enemy_w + 60;
}
//Iterate through array of enemies and draw them on the canvas
function drawEnemies() {
  for (var i = 0; i < enemies.length; i++) {
    ctx.drawImage(enemy, enemies[i][0], enemies[i][1]);
  }
}
//Iterate through array of enemies and update their position
function moveEnemies() {
  for (var i = 0; i < enemies.length; i++) {
    if (enemies[i][1] < height) {
      enemies[i][1] += enemies[i][4];
    } else if (enemies[i][1] > height - 1) {
      //after the enemies scroll off screen, this value is where they get re-spawned
      enemies[i][1] = -45;
    }
  }
}
//Check for laser collision
function hitTest() {
  var remove = false;
  for (var i = 0; i < lasers.length; i++) {
    for (var j = 0; j < enemies.length; j++) {
      //laser's y position is less than or equal to the enemy's y position plus its height -AND-
      //laser's x position is greater than or equal to the enemy's x position -AND-
      //laser's x position is less than or equal to the enemy's x position plus it's width
      if (lasers[i][1] <= (enemies[j][1] + enemies[j][3]) && lasers[i][0] >= enemies[j][0] && lasers[i][0] <= (enemies[j][0] + enemies[j][2])) {
        remove = true;
        //draw();//hier explosion afspelen
        enemies.splice(j, 1); //enemy at this array position no longer gets drawn
        enemies.push([(Math.random() * 500) + 50, -45, enemy_w, enemy_h, speed]); //refill a new enemy in a random x position between 50 and 500
      }
    }
    if (remove == true) {
      lasers.splice(i, 1);  //laser at this array position no longer gets drawn
      remove = false;
      score += 10;
    }
  }
}

这是我定义图片的代码

//wereld
var canvas;
var ctx;
var width = 600;
var height = 600;
var starfield;
var starX = 0;
var starY = 0;
var starY2 = -600;
//scoring
var score = 0;
var alive = true;
var lives = 3;
var gameStarted = false;
image = new Image()
image.src = 'explosion.png';
//Clear the canvas, this is required before each canvas frame update
function clearCanvas() {
  ctx.clearRect(0, 0, width, height);
}
//Initialize image objects, canvas, and event listeners
function init() {
  canvas = document.getElementById('canvas');
  ctx = canvas.getContext('2d');
  enemy = new Image();
  enemy.src = 'enemy.png';
  ship = new Image();
  ship.src = 'ship.png';
  starfield = new Image();
  starfield.src = 'starfield.jpg';
  document.addEventListener('keydown', keyDown, false);
  document.addEventListener('keyup', keyUp, false);
  canvas.addEventListener('click', gameStart, false);
  gameLoop();
}
//Used by an event listener.  Removes the overall canvas listener once game has started.
function gameStart() {
  gameStarted = true;
  canvas.removeEventListener('click', gameStart, false);
}
//Game loop that calls all the functions needed to be updated
function gameLoop() {
  clearCanvas();
  drawStarfield();
  if (alive && gameStarted && lives > 0) {
    hitTest();
    moveEnemies();
    moveLaser();
    drawEnemies();
    drawShip();
    drawLaser();
    shipCollision();
  }
  scoreTotal();
  //game = setTimeout(gameLoop, 1000 / 30); //not sure why 'game =' is included...
  setTimeout(gameLoop, 1000 / 30); //this works too...
}
//Used to draw several text and shape objects for score, lives, and pre-game information.
function scoreTotal() {
  ctx.font = 'bold 18px VT323';
  ctx.fillStyle = '#fff';
  ctx.fillText('Score: ', 10, 55);
  ctx.fillText(score, 70, 55);
  ctx.fillText('Lives: ', 10, 30);
  ctx.fillText(lives, 68, 30);
  if (!alive) {
    ctx.fillText('Game Over!', 245, (height / 2));
    //Continue button
    ctx.fillRect((width / 2) - 65, (height / 2) + 10, 100, 40);
    ctx.fillStyle = '#000';
    ctx.fillText('Opnieuw?', 252, (height / 2) + 35);
    canvas.addEventListener('click', continueButton, false);
  }
  //Pre-Game Text
  if (!gameStarted) {
    ctx.font = 'bold 50px VT323';
    ctx.fillText('Sander Gouman top down', (width / 2) - 210, (height / 2));
    ctx.font = 'bold 20px VT323';
    ctx.fillText('Klik om te spelen', (width / 2) - 56, (height / 2) + 30);
    ctx.fillText('Beweeg met de pijltjes', (width / 2) - 100, (height / 2) + 60);
    ctx.fillText('Gebruik de spatiebalk om te schieten', (width / 2) - 100, (height / 2) + 90);
  }
}
//Used by an event listener.  Detects if mouse click is within a specific area.
function continueButton(e) {
  var cursorPos = getCursorPos(e);
  if (cursorPos.x > (width / 2) - 53 && cursorPos.x < (width / 2) + 47 && cursorPos.y > (height / 2) + 10 && cursorPos.y < (height / 2) + 50) {
    alive = true;
    lives = 3;
    reset();
    canvas.removeEventListener('click', continueButton, false);
  }
}
//Used for detection of mouse click on canvas
function getCursorPos(e) {
  var x;
  var y;
  if (e.pageX || e.pageY) {
    x = e.pageX;
    y = e.pageY;
  } else {
    x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  }
  x -= canvas.offsetLeft;
  y -= canvas.offsetTop;
  var cursorPos = new cursorPosition(x, y);
  return cursorPos;
}
//Store x and y cursor position
function cursorPosition(x, y) {
  this.x = x;
  this.y = y;
}
//Check lives
function checkLives() {
  lives -= 1;
  if (lives > 0) {
    reset();
  } else if (lives == 0) {
    alive = false;
  }
}
//Reset enemies and player back to default position
function reset() {
  var enemy_reset_x = 50;
  ship_x = (width / 2) - 25;
  ship_y = height - 75;
  ship_w = 50;
  ship_h = 57;
  for (var i = 0; i < enemies.length; i++) {
    enemies[i][0] = enemy_reset_x;
    enemies[i][1] = -45;
    enemy_reset_x = enemy_reset_x + enemy_w + 60;
  }
}
//Draw a continuous, scrolling starfield (using two instances)
function drawStarfield() {
  ctx.drawImage(starfield, starX, starY);
  ctx.drawImage(starfield, starX, starY2);
  if (starY > 600) {
    starY = -599;
  }
  if (starY2 > 600) {
    starY2 = -599;
  }
  starY += 1;
  starY2 += 1;
}
//Initialize canvas when page is loaded
window.onload = init;

希望你们能帮忙,这样我就能得到更多敌人的

一个想法是,与其将敌方属性存储在全局范围内,不如考虑将属性存储在敌方对象中。

最简单的方法是创建一个类似的函数

 //enemies could be in global scope or 
 //inside a closure that contains everything related to the enemies
var enemies = [];
function spawnenemy(x,y,s,i) {
   var enemy = {
    xcord: x,
    ycord: y,
    speed: s,
    spriteimg: new Image()
   };
   enemy['spriteimg'].src = i;
   enemies.push(enemy);
}

然后把每个敌人的物体传给你的游戏功能,操纵你的敌人。

例如,如果你想在敌人死亡时更改敌人的图像,那么就有这样的功能。

function showDead(enemy) {
     //Notice how I am accessing the image property of the enemy...
     enemy['spriteImgUrl'].src = "dead.jpg";
     //do your thing to refresh your canvas to show the new image 
     //or register showDead function with a listener that will do it for you
 }

并简单地将应该死亡的敌人传递给这个函数,以表明它被杀死了。

希望它能给你一些想法。

我建议将每个"Enemy"视为自己的对象,为了能够定义对象,您需要创建自己的Enemy类:

function Enemy() {
  // stick this at the top of your code somewhere.
  // this defines an Enemy "class", which allows
  // you to make "new" Enemy instances
}

一旦你有了这些,你就可以制造"新"敌人,并为他们分配你喜欢的任何属性。。。偶数功能:

var enemy1 = new Enemy();
var enemy2 = new Enemy();
enemy1.x = 50;
enemy2.x = 50;
// ... fill in the rest of the stuff here
enemy1.speed = 3;
enemy2.speed = 5;
enemy1.image = new Image();
enemy1.image.src = 'enemyShip1.png';
enemy2.image = new Image();
enemy2.image.src = 'enemyShip2.png';
enemy1.getKilledByPlayer = function() {
  // give the player some score, for example
  // and/or remove this enemy from the game
};
enemies.push(enemy1);
enemies.push(enemy2);

这里的关键是,当你绘制每个敌人时,你可以使用你制作的对象(如果你把它们放在阵列中,则是enemy1enemy2enemies[i])来查找它的所有东西:

function drawEnemies() {
  for (var i = 0; i < enemies.length; i++) {
    ctx.drawImage(enemies[i].image, enemies[i].x, enemies[i].y);
    // here, saying enemies[i].image is grabbing the exact image you want
    // from when you made enemy1/enemy2 up above
  }
}

由于你推到阵列中的每个敌人都可以有不同的x、y、图像、速度等值……它们在屏幕上看起来都会是你想要的样子,这取决于你给它们的值。