게임 중력


일부 게임에는 중력이 물체를 지면으로 당기는 것처럼 게임 구성요소를 한 방향으로 당기는 힘이 있습니다.




중력

이 기능을 구성 요소 생성자에 추가하려면 먼저 gravity현재 중력을 설정하는 속성을 추가합니다. 그런 다음 gravitySpeed프레임을 업데이트할 때마다 증가하는 속성을 추가합니다.

예시

function component(width, height, color, x, y, type) {
  this.type = type;
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.speedX = 0;
  this.speedY = 0;
  this.gravity = 0.05;
  this.gravitySpeed = 0;
 
this.update = function() {
    ctx = myGameArea.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
  }
}


바닥을 치다

빨간색 사각형이 영원히 떨어지는 것을 방지하려면 게임 영역의 바닥에 닿을 때 떨어지는 것을 멈춥니다.

예시

  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
  }
  this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
      this.y = rockbottom;
    }
  }


가속

게임에서 아래로 당기는 힘이 있을 때 구성 요소를 강제로 가속하는 방법이 있어야 합니다.

누군가 버튼을 클릭하면 함수를 트리거하고 빨간색 사각형이 공중으로 날아가도록 합니다.

예시

<script>
function accelerate(n) {
  myGamePiece.gravity = n;
}
</script>

<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>

게임

지금까지 배운 내용을 바탕으로 게임을 만드세요.

예시