WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Game Gravity



A few recreations have powers that pulls the amusement segment one way, similar to gravity destroys articles to the ground.




Gravity

To add this usefulness to our segment constructor, first include a gravity property, which sets the present gravity. At that point include a gravitySpeed property, which increments everytime we update the frame:

Example

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;
    }
}

Hit the Bottom

To prevent the red square from falling forever, stop the falling when it hits the bottom of the game area:

Example

    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;
        }
    }


Accelerate Up

In a game, when you have a force that pulls you down, you should have a method to force the component to accelerate up.

Trigger a function when someone clicks a button, and make the red square fly up in the air:

Example

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

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