【问题标题】:libGDX: How to implement a smooth tile / grid based game character movement?libGDX:如何实现基于平铺/网格的游戏角色移动?
【发布时间】:2014-01-24 13:02:27
【问题描述】:

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

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

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

我会很高兴看到一些已经实现的示例,这些示例可以进行研究并导致正确的 libGDX API 使用。

【问题讨论】:

标签: java android windows libgdx tiled


【解决方案1】:

测试是否按下了特定的按钮(或触摸了屏幕),如果是,则在一个区域中设置正确的目标图块(玩家将要去的图块)并开始移动到那里,只有当玩家在下一个图块中。发生这种情况时,请再次检查输入以继续移动(即重复)。

假设您的图块宽度/高度为 1,并且您希望每秒移动 1 个图块。您的用户按下了右箭头键。然后,您只需将 targettile 设置为播放器右侧的图块。

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

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

编辑:

输入轮询键:

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

InputPolling for touchs(cam 是你的相机,touchPoint 是一个 Vector3 来存储未投影的触摸坐标,moverightBounds 一个 (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 作为参数获取,或者您可以在其他任何地方使用:

Gdx.graphics.getDeltatime();

参考文献:

【讨论】:

  • 感谢您的帮助。您能否再解释一下从哪里调用该代码以及如何进行输入轮询?此外,我不确定如何根据不断变化的帧速率计算delta
  • @JensPiegsa 您通过 LibGDX 获取增量作为您的 render() 方法中的参数。否则,您可以通过 Gdx.graphics.getDeltaTime() 获取它。
  • 编辑了我的答案 :) 你在渲染方法中调用它(每一帧)
  • 再次感谢您提供实际解决方案的基本提示。
【解决方案2】:

这仅适用于一个维度,但我希望您明白这一点,通过检查方向键并加/减 1,然后将其转换为 int(或地板)将为您提供下一个图块。如果您释放键,您仍然有一个未到达的目标,实体将继续移动,直到它到达目标图块。我认为它看起来像这样:

void update()(
    // Getting the target tile
    if ( rightArrowPressed ) {
        targetX = (int)(currentX + 1); // Casting to an int to keep 
                                       // the target to next tile
    }else if ( leftArrowPressed ){
        targetX = (int)(currentX - 1);
    }

    // Updating the moving entity
    if ( currentX < targetX ){
        currentX += 0.1f;
    }else if ( currentX > targetX ){
        currentX -= 0.1f;
    }
}

【讨论】:

  • 这正是我几个小时前回答的……这使用了一个固定的步长,而不是使用帧之间传递的时间来实现帧独立运动。
  • 抱歉,我发布回复时看不到您的回答。
猜你喜欢
  • 1970-01-01
  • 2022-07-26
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多