게임 장애물


버튼을 눌러 빨간색 사각형을 이동합니다.







장애물 추가

이제 게임에 몇 가지 장애물을 추가하고 싶습니다.

게임 영역에 새 구성 요소를 추가합니다. 녹색, 너비 10px, 높이 200px로 만들고 오른쪽으로 300px, 아래로 120px 배치합니다.

또한 모든 프레임에서 장애물 구성요소를 업데이트합니다.

예시

var myGamePiece;
var myObstacle;

function startGame() {
  myGamePiece = new component(30, 30, "red", 10, 120);
  myObstacle = new component(10, 200, "green", 300, 120);
  myGameArea.start();
}

function updateGameArea() {
  myGameArea.clear();
  myObstacle.update();
  
myGamePiece.newPos();
  myGamePiece.update();
}


장애물에 부딪히다 = 게임 오버

위의 예에서 장애물에 부딪혀도 아무 일도 일어나지 않습니다. 게임에서는 그다지 만족스럽지 않습니다.

빨간색 사각형이 장애물에 부딪혔는지 어떻게 알 수 있습니까?

구성 요소가 다른 구성 요소와 충돌하는지 확인하는 새 메서드를 구성 요소 생성자에 만듭니다. 이 메서드는 프레임이 업데이트될 때마다 초당 50번 호출되어야 합니다.

또한 20밀리초 간격을 지우는 stop()메서드를 myGameArea개체에 추가합니다.

예시

var myGameArea = {
  canvas : document.createElement("canvas"),
  start : function() {
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.interval = setInterval(updateGameArea, 20);
  },
  clear : function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  },
  stop : function() {
    clearInterval(this.interval);
  }
}

function component(width, height, color, x, y) {
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.newPos = function() {
    this.x += this.speedX;
    this.y += this.speedY;
  }
  this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) ||
    (mytop > otherbottom) ||
    (myright < otherleft) ||
    (myleft > otherright)) {
      crash = false;
    }
    return crash;
  }
}

function updateGameArea() {
  if (myGamePiece.crashWith(myObstacle)) {
    myGameArea.stop();
  } else {
    myGameArea.clear();
    myObstacle.update();
    myGamePiece.newPos();
    myGamePiece.update();
  }
}

움직이는 장애물

장애물은 정적일 때 위험하지 않으므로 이동하기를 원합니다.

myObstacle.x업데이트할 때마다 의 속성 값을 변경합니다 .

예시

function updateGameArea() {
  if (myGamePiece.crashWith(myObstacle)) {
    myGameArea.stop();
  } else {
    myGameArea.clear();
    myObstacle.x += -1;
    myObstacle.update();
    myGamePiece.newPos();
    myGamePiece.update();
  }
}

여러 장애물

여러 장애물을 추가하는 것은 어떻습니까?

이를 위해서는 프레임을 계산하는 속성과 주어진 프레임 속도로 무언가를 실행하는 메서드가 필요합니다.

예시

var myGameArea = {
  canvas : document.createElement("canvas"),
  start : function() {
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.frameNo = 0;       
    this.interval = setInterval(updateGameArea, 20);
  },
  clear : function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  },
  stop : function() {
    clearInterval(this.interval);
  }
}

function everyinterval(n) {
  if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
  return false;
}

everyinterval 함수는 현재 프레임 번호가 지정된 간격과 일치하면 true를 반환합니다.

여러 장애물을 정의하려면 먼저 장애물 변수를 배열로 선언하십시오.

둘째, updateGameArea 함수에서 몇 가지를 변경해야 합니다.

예시

var myGamePiece;
var myObstacles = [];

function updateGameArea() {
  var x, y;
  for (i = 0; i < myObstacles.length; i += 1) {
    if (myGamePiece.crashWith(myObstacles[i])) {
      myGameArea.stop();
      return;
    }
  }
  myGameArea.clear();
  myGameArea.frameNo += 1;
  if (myGameArea.frameNo == 1 || everyinterval(150)) {
    x = myGameArea.canvas.width;
    y = myGameArea.canvas.height - 200
    myObstacles.push(new component(10, 200, "green", x, y));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].x += -1;
    myObstacles[i].update();
  }
  myGamePiece.newPos();
  myGamePiece.update();
}

함수 에서 updateGameArea충돌이 있는지 확인하기 위해 모든 장애물을 반복해야 합니다. 충돌이 발생하면 updateGameArea기능이 중지되고 더 이상 그리기가 수행되지 않습니다.

updateGameArea함수는 프레임을 계산하고 150번째 프레임마다 장애물을 추가합니다.


무작위 크기의 장애물

게임을 좀 더 어렵고 재미있게 만들기 위해 임의의 크기의 장애물을 보내서 빨간색 사각형이 충돌하지 않도록 위아래로 움직여야 합니다.

예시

function updateGameArea() {
  var x, height, gap, minHeight, maxHeight, minGap, maxGap;
  for (i = 0; i < myObstacles.length; i += 1) {
    if (myGamePiece.crashWith(myObstacles[i])) {
      myGameArea.stop();
      return;
    }
  }
  myGameArea.clear();
  myGameArea.frameNo += 1;
  if (myGameArea.frameNo == 1 || everyinterval(150)) {
    x = myGameArea.canvas.width;
    minHeight = 20;
    maxHeight = 200;
    height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
    minGap = 50;
    maxGap = 200;
    gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
    myObstacles.push(new component(10, height, "green", x, 0));
    myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].x += -1;
    myObstacles[i].update();
  }
  myGamePiece.newPos();
  myGamePiece.update();
}