Game Gravity
- Previous Page Game Sounds
- Next Page Game Bounce
In some games, there is a force that pulls game components in one direction, such as gravity pulling objects towards the ground.
gravity
If you want to add this feature to our component constructor, please add a gravity
Attribute, which sets the current gravity. Then add a gravitySpeed
Properties that increase every time we update the frame:
Examples
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; } }
Touch Bottom
To prevent the red block from falling forever, we need to stop its fall when it reaches the bottom of the game area:
Examples
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
In the game, when there is a force pulling the block down, you should design a method to force the component to accelerate.
A function is triggered when someone clicks the button, making the red block fly into the air:
Examples
<script> function accelerate(n) { myGamePiece.gravity = n; } </script> <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">Accelerate</button>
A game
Make a game based on what we have learned so far:
Examples
Please click the accelerate button to start the game.
How long can you live? Please use the accelerate button to stay in the air.
- Previous Page Game Sounds
- Next Page Game Bounce