gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 14:42:45 24 4
gpt4 key购买 nike

因为害怕重新发明轮子,我想知道:

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

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

我很高兴有一些已经实现的示例可以研究并导致正确使用 libGDX API。

最佳答案

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

假设您的图 block 宽度/高度为 1,并且您希望每秒移动 1 个图 block 。您的用户按下了右箭头键。然后,您只需将目标方 block 设置为玩家右侧的方 block 即可。

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(cam 是您的相机,touchPoint 是一个 Vector3,用于存储未投影的触摸坐标,moverightBounds 是一个 (libgdx) 矩形):

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 方法中将增量作为参数获取,或者您可以在其他任何地方使用:

Gdx.graphics.getDeltatime();

引用资料:

关于java - libGDX:如何实现基于平铺/网格的游戏角色移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20961596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com