Изображения в игре

Нажмите кнопку, чтобы переместить улыбающееся лицо:






Как использовать изображения?

Чтобы добавить изображение на холст, используйте свойства и методы встроенного объекта getContext("2d").

В нашей игре, чтобы создать компонент в виде изображения, используйте конструктор компонента, но вы должны ссылаться на url изображения, а не на цвет. И вам нужно сообщить конструктору, что тип компонента - "image":

instance

function startGame() {
  myGamePiece = new component(30, 30, "smiley.gif", 10, 120, "image");
  myGameArea.start();
}

В конструкторе компонента мы проверяем, принадлежит ли компонент типу "image", и используем конструктор объекта "new Image()", чтобы создать объект изображения. При подготовке к рисованию изображения мы используем метод drawImage, а не метод fillRect:

instance

function component(width, height, color, x, y, type) {
  this.type = type;
  if (type == "image") {}}
    this.image = new Image();
    this.image.src = color;
  }
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    if (type == "image") {}}
      ctx.drawImage(this.image,
        this.x,
        this.y,
        this.width, this.height);
    } else {
      ctx.fillStyle = color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }
  }
}

Попробуйте сами

Изменение изображения

Вы можете в любое время изменить изображение, изменив компонент: image объекта src Свойства для изменения изображения.

Если вы хотите изменить улыбку при каждом движении, измените источник изображения при нажатии на кнопку и верните его в нормальное состояние при невозбуждении:

instance

function move(dir) {
  myGamePiece.image.src = "angry.gif";
  if (dir == "up") {myGamePiece.speedY = -1; }
  if (dir == "down") {myGamePiece.speedY = 1; }
  if (dir == "left") {myGamePiece.speedX = -1; }
  if (dir == "right") {myGamePiece.speedX = 1; }
}
function clearmove() {
  myGamePiece.image.src = "smiley.gif";
  myGamePiece.speedX = 0;
  myGamePiece.speedY = 0;
}

Попробуйте сами

Изображение фона

Добавьте изображение фона в качестве компонента, чтобы добавить его в зону игры и обновлять его в каждом кадре:

instance

var myGamePiece;
var myBackground;
function startGame() {
  myGamePiece = new component(30, 30, "smiley.gif", 10, 120, "image");
  myBackground = new component(656, 270, "citymarket.jpg", 0, 0, "image");
  myGameArea.start();
}
function updateGameArea() {
  myGameArea.clear();
  myBackground.newPos();
  myBackground.update();
  myGamePiece.newPos();
  myGamePiece.update();
}

Попробуйте сами

Перемещение фона

Измените компонент фона: speedX Свойства позволяют перемещать 背景:

instance

function updateGameArea() {
  myGameArea.clear();
  myBackground.speedX = -1;
  myBackground.newPos();
  myBackground.update();
  myGamePiece.newPos();
  myGamePiece.update();
}

Попробуйте сами

Background loop

To make this same background loop forever, we must use specific techniques.

Firstly, tell the component constructor that this is the background. Then, the component constructor will add the image twice, placing the second image immediately after the first image.

In newPos() In the method, check if the component's x position has reached the end of the image, if it has, then set the component's x Position set to 0:

instance

function component(width, height, color, x, y, type) {
  this.type = type;
  if (type == "image" || type == "background") {
    this.image = new Image();
    this.image.src = color;
  }
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    if (type == "image" || type == "background") {
      ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
      if (type == "background") {
        ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
      }
    }
      ctx.fillStyle = color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }
  }
  this.newPos = function() {
    this.x += this.speedX;
    this.y += this.speedY;
    if (this.type == "background") {
      if (this.x == -(this.width)) {
        this.x = 0;
      }
    }
  }
}

Попробуйте сами