최신 웹 개발 튜토리얼
 

HTML 게임 중력


일부 게임 중력 지상 물체를 끌어처럼 일방향 게임 요소를 당기는 힘이있다.




중량

우리의 구성 요소 생성자에이 기능을 추가하려면 먼저 추가 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>
»그것을 자신을 시도

게임

우리가 지금까지 배운 것을 기반으로 게임을합니다 :