创建2D物理游戏引擎(JavaScript)时遇到麻烦

时间:2020-02-08 02:14:14

标签: javascript 2d game-physics physics 2d-games

希望您一切都好。 我是一名初学者,最近我一直在使用JavaScript开发2D物理游戏引擎。直到我在推送机制中遇到一个烦人的错误之前,一切似乎都工作正常。

我创建了一个带有可碰撞方块(玩家)的推动系统,该系统可以同时推动多个其他可碰撞方块,并在方块碰到墙时停止(您不能推动)。但是,当玩家同时按下一个或多个正方形时,它们都会飞到墙壁的顶部,而距离最靠近墙壁的正方形(如视频所示)。

Project Files

Video which shows the problem

我已经尝试解决这个问题已有一段时间了,但是我找不到理想的解决方案。

如果有人能够提供帮助,那就太好了。谢谢

collisionDetection: function(game) {
    var collisionDetection = function(obj01, obj02) {
        if(obj01.x < obj02.x + obj02.colW &&
            obj01.x + obj01.colW > obj02.x &&
            obj01.y < obj02.y + obj02.colH &&
            obj01.y +obj01.colH > obj02.y) {
                physics.handleCollision(obj01, obj02);
        }
    };     

    for (let i = 0; i < game.gameComponents.length; i++) {

        for (let j = i + 1; j < game.gameComponents.length; j++) {
            const obj01 = game.gameComponents[i];
            const obj02 = game.gameComponents[j];
            collisionDetection(obj01, obj02);
        }
    }
},

    handleCollision: function(obj01, obj02) {

    var tr = obj01.x + obj01.colW // This right side
    var tl = obj01.x // This left
    var tt = obj01.y // This top

    var or = obj02.x + obj02.colW // Other right
    var ol = obj02.x // Other left
    var ot = obj02.y // Other top

    // North, east, south, west of other (around)
    if (obj02.colType == "nesw") {

        // Top of other
        if(obj01.y+obj01.colH>obj02.y && tl + obj01.colW > obj02.x+3 && tl < obj02.x+obj02.colW-3) {
            obj01.y = obj02.y - obj01.colH;
        }
        // Bottom of other
        if(tr > ol + 3 && tl < or - 3 && tt > ot) {
            obj01.y = obj02.y + obj02.colH;
        }
        // Left of other
        if(tl < obj02.x && obj01.y + obj01.colH > obj02.y && obj01.y < obj02.y + obj02.colH) {
            if (obj02.pushable == true ) {

                obj02.x = (obj01.x + obj01.colW) 

            }else {
                obj01.x = (obj02.x - obj01.colW) 
            }


        }
        // right of other
        if(tl > obj02.x && obj01.y + obj01.colH > obj02.y && obj01.y < obj02.y + obj02.colH) {
            obj01.x = obj02.x + obj02.colW;
        }

    }

0 个答案:

没有答案
相关问题