Skip to content
Loading
gravity Property in HTML 5
  • Dipa Mehta
    Thanks For these code snippets, it’s the explanation in itself.
    +1
  • Bidyasagar Mishra
    for more refernces try the below link
    https://www.dummies.com/programming/programming-games/how-to-add-gravity-to-your-html5-game/ 
    0
  • Bidyasagar Mishra
    1. >  
    2. <html>  
    3. <head>  
    4. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>  
    5. <style>  
    6. canvas {  
    7.     border:1px solid #d3d3d3;  
    8.     background-color: #f1f1f1;  
    9. }  
    10. style>  
    11. head>  
    12. <body onload="startGame()">  
    13. <script>  
    14.   
    15. var myGamePiece;  
    16.   
    17. function startGame() {  
    18.     myGamePiece = new component(30, 30, "red", 80, 75);  
    19.     myGameArea.start();  
    20. }  
    21.   
    22. var myGameArea = {  
    23.     canvas : document.createElement("canvas"),  
    24.     start : function() {  
    25.         this.canvas.width = 480;  
    26.         this.canvas.height = 270;  
    27.         thisthis.context = this.canvas.getContext("2d");  
    28.         document.body.insertBefore(this.canvas, document.body.childNodes[0]);  
    29.         this.interval = setInterval(updateGameArea, 20);          
    30.     },  
    31.     stop : function() {  
    32.         clearInterval(this.interval);  
    33.     },      
    34.     clear : function() {  
    35.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);  
    36.     }  
    37. }  
    38.   
    39. function component(width, height, color, x, y, type) {  
    40.     this.type = type;  
    41.     this.width = width;  
    42.     this.height = height;  
    43.     this.x = x;  
    44.     this.y = y;      
    45.     this.speedX = 0;  
    46.     this.speedY = 0;      
    47.     this.gravity = 0.05;  
    48.     this.gravitySpeed = 0;  
    49.     this.update = function() {  
    50.         ctx = myGameArea.context;  
    51.         ctx.fillStyle = color;  
    52.         ctx.fillRect(this.x, this.y, this.width, this.height);  
    53.     }  
    54.     this.newPos = function() {  
    55.         this.gravitySpeed += this.gravity;  
    56.         this.x += this.speedX;  
    57.         this.y += this.speedY + this.gravitySpeed;          
    58.     }  
    59. }  
    60.   
    61. function updateGameArea() {  
    62.     myGameArea.clear();  
    63.     myGamePiece.newPos();  
    64.     myGamePiece.update();  
    65. }  
    66.   
    67. script>  
    68.   
    69. <p>Gravity makes the red square fall to the ground and beyond.p>  
    70.   
    71. body>  
    72. html>  
    0