게임 이동

Game Rotation 장에서 설명한 새로운 방식으로 구성 요소를 그리면 움직임이 더 유연해집니다.


개체를 이동하는 방법?

구성 요소의 현재 속도를 나타내는 speed속성을 생성자에 추가합니다 .component

또한 및 newPos()에 기반하여 구성요소의 위치를 ​​계산하기 위해 방법 을 약간 변경합니다 .speedangle

기본적으로 구성 요소는 위를 향하고 있으며 속도 속성을 1로 설정하면 구성 요소가 앞으로 이동하기 시작합니다.

예시

function component(width, height, color, x, y) {
  this.gamearea = gamearea;
  this.width = width;
  this.height = height;
  this.angle = 0;
  this.speed = 1;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.fillStyle = color;
    ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
    ctx.restore();
  }
  this.newPos = function() {
    this.x += this.speed * Math.sin(this.angle);
    this.y -= this.speed * Math.cos(this.angle);
  }
}


회전하기

우리는 또한 좌회전과 우회전을 할 수 있기를 원합니다. moveAngle현재 이동 값 또는 회전 각도를 나타내는 이라는 새 속성을 만듭니다 . newPos()메서드 에서 속성 angle을 기반으로 계산합니다.moveAngle

예시

moveangle 속성을 1로 설정하고 어떤 일이 일어나는지 확인하십시오:

function component(width, height, color, x, y) {
  this.width = width;
  this.height = height;
  this.angle = 0;
  this.moveAngle = 1;
  this.speed = 1;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.fillStyle = color;
    ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
    ctx.restore();
  }
  this.newPos = function() {
    this.angle += this.moveAngle * Math.PI / 180;
    this.x += this.speed * Math.sin(this.angle);
    this.y -= this.speed * Math.cos(this.angle);
  }
}

키보드 사용

키보드를 사용할 때 빨간색 사각형은 어떻게 움직이나요? 위, 아래, 좌우로 움직이는 대신 "위" 화살표를 사용하면 빨간색 사각형이 앞으로 이동하고, 왼쪽 및 오른쪽 화살표를 누르면 왼쪽과 오른쪽으로 회전합니다.

예시