게임 중력

일부 게임에서는 게임 요소를 한 방향으로 끌어당기는 중력과 같은 힘이 존재합니다.


중력

이 특성을 我们的 구성 함수에 추가하려면 먼저 추가하십시오. 중력 속성, 이 속성은 현재의 중력을 설정합니다. 그런 다음 추가하십시오. 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 ускорить(n) {
  myGamePiece.gravity = n;
}
</script>
<button onmousedown="ускорить(-0.2)" onmouseup="ускорить(0.1)">Ускорение</button>

직접 시험해 보세요

한 개의 게임

지금까지 배운 지식을 바탕으로 게임을 만들어 보세요:

예제

직접 시험해 보세요

게임을 시작하기 위해 가속 버튼을 클릭하세요.

얼마나 오래 살 수 있을까요? 공간을 유지하기 위해 가속 버튼을 사용하세요.