0
votes

I'm working on a simple html5 platformer, building of a previous game but having trouble with collisions and physics. below is a sample of code regarding the floor and how it handles collisions. the full code is here. http://www.ambitiongames.co.uk/dev/game.php with the game being here http://www.ambitiongames.co.uk/dev/

the problem I'm having is the collisions are based on events grabbing which sometimes leaves the player in the floor not on it.

also, due to the way jumping and falling work there's no gravity, meaning a player can simply jump on a higher ledge and then walk off into the air.

whats the a good way to set up a permanent state of gravity ?

whats a good way to interact / collide with the floor or other objects ?

        that.draw = function(){  
            try {  
                ctx.drawImage(that.image, that.x, that.y, that.width, that.height);  
                } catch (e) {  
                }  
        } 
        return that;  
    };

    var nrOffloors = 40,   
        floors = [],  
        floorWidth = 20,  
        floorHeight = 40;  
        var generatefloor = function(){  

            for (var i = 0; i < 10; i++) {  
                floors[i] = new Floor(i * 20,280);   
            } 
            for (var i = 10; i < 12; i++) {  
                floors[i] = new Floor(i * 20,260);   
            } 
        }();

    var checkCollisionfloor = function(){  
        floors.forEach(function(e, ind){  
            if (   
                (player.X < e.x + floorWidth) &&   
                (player.X + player.width > e.x) &&   
                (player.Y + player.height > e.y) &&   
                (player.Y + player.height < e.y + floorHeight)  

                ) {  
                    e.onCollide();  
                } 
        });     
    } 
1
I can't load the game, and this is a pretty broad question, but you'll benefit extraordinarily from utilizing a traditional object-oriented approach when designing games like this. This way each object (player and/or anything else) can keep track of their own velocity and acceleration and the calculations for gravity should be pretty trivial. You essentially are just adding the constant negative acceleration due to gravity to the objects existing acceleration, and you can keep track of the player's Y position to ensure they don't fall below 0 (the ground) - Cecchi
... To simulate hitting the ground you can invert their velocity, which will cause the player to bounce a bit, with gravity eventually holding them down. - Cecchi
i see what your saying so instead of var Floor = function(x, y){ insert stuff here it should be var StartButton = new Object(); and add variables accordingly ? - Rudiger Kidd

1 Answers

1
votes

You can try a library like Box2D.js. It handles everything from collision detection to gravity.

Check out it's demos.