繁体   English   中英

Android libgdx游戏中的图块碰撞检测

[英]Tile collision detection in Android libgdx game

到目前为止,我正在写这个游戏,我只是使用瓦片来处理碰撞检测:

我将地图向左滚动8个单位。 然后,我检查角色右侧是否与具有“碰撞”属性的图块发生碰撞。 如果发生碰撞,则将角色定位为使其右边缘像素值等于图块的左边缘。

现在要检查垂直碰撞检测,我同时检查了角色的右下角和左下角。 如果任一角在“碰撞”图块中,则将字符的y值设置为等于图块的顶部(即,如果它与实心图块发生碰撞,则它将始终出现在该图块的顶部)。

这种垂直碰撞检测一直有效,直到碰到墙为止。 由于垂直碰撞检查将始终将角色推到图块的顶部,因此如果我的角色跳跃并降落在墙的中心,则他将被卡在墙中图块之一的顶部,直到您按“跳转”,然后他立即移至下一个图块的顶部。

解决此垂直碰撞检测的更好方法是什么? 我一直在考虑永远不要让角色完全拥抱“墙”图块,以使他的右边缘总是距墙图块左1像素,这样我仍然可以检查角色的右角及其永远不会真正撞到那堵墙(因此,如果靠近墙,角色可能仍会掉下来)。 不过这似乎草率。 有没有更好的办法? 我整天都在研究,但似乎找不到很好的解决方案。

代码如下所示:

public void render() 
{       

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    gameTime += Gdx.graphics.getDeltaTime();

    characterDisplay = characterAnimation.getKeyFrame(gameTime, true);




    TiledMapTileLayer layer = (TiledMapTileLayer)tiledMap1.tiledMap.getLayers().get(0);

    float x;
    float x1; 
    float x2;
    x1 = ((characterPosition.x + characterWidth)/tileWidth);
    x2 = (-tileRenderer.tiledMap.x); 
    x = x1 + x2;


    if (isFalling)
        characterPosition.y -= FALLING_SPEED;

    float yBottom;
    float y1 = (int)((characterPosition.y)/tileWidth) + 1; 
    yBottom = y1;



    tileRenderer.tiledMap.x -= .2;


    if (layer.getCell((int)x, (int)yBottom).getTile().getProperties().containsKey("collision"))
    {
        characterPosition.x = ((x + tileRenderer.tiledMap.x )* tileWidth) - characterWidth;
    }


    y1 = (int)(characterPosition.y/tileWidth);
    yBottom = y1;

    x1 = ((characterPosition.x + characterWidth)/tileWidth);
    x2 = (-tileRenderer.tiledMap.x); 
    x = x1 + x2;    

    if ((layer.getCell((int)x, (int)yBottom).getTile().getProperties().containsKey("collision") || layer.getCell((int)x - 1, (int)yBottom).getTile().getProperties().containsKey("collision")))
    {

        characterPosition.y = (yBottom * tileHeight) + tileHeight;
        isFalling = false;
    }

    tileRenderer.render();      




    //draw textures
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(characterDisplay, characterPosition.x, characterPosition.y);
    batch.end();


    //handle user input
    handleUserInput();
}

您可能要考虑将字符“推”出图块,而不是简单地将字符设置在与之碰撞的图块“外部”。 因此,如果您跳入墙壁,代码将识别您先前的位置和运动矢量,并意识到您首先在x方向上发生碰撞。 然后,您的演员将沿着其运动矢量“向后推”,直到它碰到与其碰撞的对象为止。 然后再次检查以确保没有碰撞任何东西,然后重复。 这也应有助于确保您不会将角色嵌入墙/地板中。

有效地,尝试迭代而不是一次全部。

您也可以抢先做事-也就是说,在搬家之前先检查一下。 请参阅此处的示例。

还有box2d,对于这种级别的复杂性,它很快就会变得有用。 它比起自己的手枪来进行碰撞检测要干净得多,并且对平台游戏机来说是很棒的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM