解决简单 TypeScript 游戏引擎中的冲突

问题描述 投票:0回答:1

我目前正在用 TypeScript 创建一个简单的游戏引擎/框架。到目前为止一切正常,我什至实现了多人游戏,但这是我的 Colision 检测中断的地方。简而言之:较早加入的玩家可以推动较晚加入的玩家,但反之则不行。理想的行为是两个玩家在碰撞时都停下来。

引擎有一个

update()
函数,它在每次滴答时被调用。然后这个函数遍历一组游戏对象并调用它们各自的更新函数。我没有实现适当的物理,我宁愿像这样移动玩家的 X 和 Y 位置。

this.transform.position().y += Player.speed * deltaTime();

位置更新完成后,我解决了这样的冲突:

this.collidesWith(GameObject, (collider: GameObject) => {
    let distances = {
        left: (this.transform.position().x) - (collider.transform.position().x + collider.getSize().width) ,
        top: (this.transform.position().y) - (collider.transform.position().y + collider.getSize().height),
        right: (this.transform.position().x + this.getSize().width) - (collider.transform.position().x),
        bottom: (this.transform.position().y + this.getSize().height) - (collider.transform.position().y),
    }
    let abs = {
        left: Math.abs(distances.left),
        top: Math.abs(distances.top),
        right: Math.abs(distances.right),
        bottom: Math.abs(distances.bottom),
    }

    let dir = Math.min(abs.left,  abs.top,  abs.right, abs.bottom);

    if(dir == abs.left){
        collider.transform.updateX(distances.left);
    }
    if(dir == abs.top){
        collider.transform.updateY(distances.top);
    }
    if(dir == abs.right){
        collider.transform.updateX(distances.right);
    }
    if(dir == abs.bottom){
        collider.transform.updateY(distances.bottom);
    }
})

但问题是首先生成的对象(在我的例子中是首先连接的玩家)将能够推动后来加入的玩家,因为它首先得到解决。我已经尝试过不直接移动它们,而是先计算所有内容然后再解决,但问题仍然存在。

我知道为什么我的代码有这个问题,但我真的不确定什么是解决它的最佳方法。如前所述,我只是希望玩家一进入另一个玩家就停下来。

javascript typescript collision-detection game-physics game-engine
1个回答
0
投票

这样做:

foreach player:
    move
    collide with other players

代替:

foreach player:
    move

foreach player:
    collide with other players

然后第一个玩家会移动,被其他玩家推,然后第二个玩家也会这样做。

所以如果一个玩家移动到另一个玩家那里它停止移动然后其他玩家做同样的事情:移动到玩家停止移动(被推回)。这样一来,任何玩家都不会优先于其他玩家。

© www.soinside.com 2019 - 2024. All rights reserved.