libGDX:如何实现平滑的瓷砖/基于网格的游戏角色动作?网格、平滑、瓷砖、如何实现

2023-09-06 09:05:27 作者:散落星河的记忆

在恐惧重新发明轮子的,我想知道:

In fear of reinventing the wheel, I wonder:

什么是实施自上而下的平稳基于网格的游戏角色动作的瓷砖的(2D)地图的最佳方法的 libGDX 的?

What is the best approach to implement a smooth grid based game character movement on a top-down Tiled (2D) map with libGDX?

的字符应当保持尽可能长地砖之间平滑移动如箭头键是pressed(或触摸事件occures上的字符的特定方向),并应完成局限于上键/触摸释放的网格位置。运动应该是独立于帧速率

The character should keep moving smoothly between tiles as long as an arrow key is pressed (or a touch event occures on certain direction of the character) and should finish confined to a grid position on key / touch release. The movement should be independent from the frame rate.

我将很高兴对可以进行研究,并导致适当的libGDX API使用一些已经实施的例子。

I would be glad about some already implemented examples that can be studied and lead to a proper libGDX API usage.

推荐答案

测试一个特定的按钮被pressed(或屏幕触摸),如果是,设置正确的目标瓷砖(瓷砖,玩家将去)中的一个领域,并开始移动那里,此运动将仅当玩家在下一瓦片结束。如果出现这种情况,请检查输入再继续前进(即重复)。

Test if a specific button is pressed (or screen touched), if it is, set the correct target tile (the tile where the player will go) in a field and start moving there, this Movement will only end when the player is in the next tile. When that happens, check for input again to keep moving (i.e. repeat).

让我们假设,你的瓷砖宽/高为1,要移动每秒1瓦。您的用户pressed右箭头键。然后你只需设置targettile的瓷砖恰到好处的球员。

Lets suppose, your tile width/height is 1, and you want to move 1 tile per second. Your user pressed Right arrow key. Then you just set the targettile to the tile just right of the player.

if(targettile!=null){
    yourobject.position.x += 1*delta;
    if(yourobject.position.x>=targettile.position.x){
        yourobject.position.x = targettile.position.x;
        targettile = null;
    }
}

这code被简化为向右运动而已,你需要使它在其他方向了。结果不要忘记轮询如果再播放器不移动输入。

This code is simplified for right movement only, you need to make it for the other directions too. Dont forget to poll the input again if the player is not moving.

编辑:

InputPolling钥匙:

InputPolling for keys:

if (Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)){

InputPolling为沾上(凸轮是你的摄像头,接触点是一个的Vector3存储未投影触摸坐标和moverightBounds一(libgdx)矩形):

InputPolling for touchs (cam is your camera, and touchPoint is a Vector3 to store the unprojected touch coordinates, and moverightBounds a (libgdx) Rectangle):

if (Gdx.input.isTouched()){
    cam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
    //check if the touch is on the moveright area, for example:
    if(moveRightBounds.contains(touchPoint.x, touchPoint.y)){
        // if its not moving already, set the right targettile here
    }
}

和没有人已经说了,你得到的三角洲作为一个参数的渲染方法,或者你可以得到它在其他地方使用:

And noone already said it, you get the delta as a parameter in the render method, or you can get it anywhere else using:

Gdx.graphics.getDeltatime();

参考文献:

InputPolling InputPolling