libGDX:如何实现基于平铺/网格的游戏角色移动?

2022-01-12 00:00:00 windows android java libgdx tiled

由于害怕重新发明轮子,我想知道:

In fear of reinventing the wheel, I wonder:

使用 libGDX 在自上而下的 Tiled (2D) 地图上实现基于平滑网格的游戏角色移动的最佳方法是什么?

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

只要按下箭头键(或在角色的某个方向上发生触摸事件),角色就应该在图块之间保持平稳移动,并且应该在键/触摸释放时完成限制在网格位置.移动应该独立于帧速率.

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.

推荐答案

测试特定按钮是否被按下(或屏幕被触摸),如果是,则在场并开始移动到那里,这个移动只会在玩家在下一个图块中时结束.发生这种情况时,请再次检查输入以继续移动(即重复).

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 个图块.您的用户按下了右箭头键.然后,您只需将 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;
    }
}

此代码仅针对向右移动进行了简化,您也需要针对其他方向进行此代码.
如果玩家没有移动,不要忘记再次轮询输入.

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.

输入轮询键:

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

InputPolling for touchs(cam 是你的相机,touchPoint 是一个 Vector3 来存储未投影的触摸坐标,moverightBounds 一个 (libgdx) Rectangle):

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
    }
}

并且 noone 已经说过了,您在 render 中将 delta 作为参数方法,或者您可以在其他任何地方使用:

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

相关文章