为了避免重复造轮子,我想知道:
在libGDX上,如何实现一个基于网格的游戏角色平滑移动的最佳方法?该游戏是基于Tiled(2D)地图的。
只要按下箭头键(或者角色朝某个方向发生触摸事件),角色就应该在瓷砖之间平滑移动,并在松开键盘/触摸时停留在网格位置上。这种运动应该与帧率无关。
如果有一些已经实现的例子可以供学习,并指导正确使用libGDX API,那将非常感激。
为了避免重复造轮子,我想知道:
在libGDX上,如何实现一个基于网格的游戏角色平滑移动的最佳方法?该游戏是基于Tiled(2D)地图的。
只要按下箭头键(或者角色朝某个方向发生触摸事件),角色就应该在瓷砖之间平滑移动,并在松开键盘/触摸时停留在网格位置上。这种运动应该与帧率无关。
如果有一些已经实现的例子可以供学习,并指导正确使用libGDX API,那将非常感激。
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)){
输入轮询触摸(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方法中将delta作为参数传入,或者在任何其他地方使用以下方法获取:
Gdx.graphics.getDeltatime();
参考资料:
这只是针对一维的情况,但我希望你能理解这个思路。通过检查方向键并加/减1,然后将其转换为int(或floor)将给出下一个瓷砖。如果你松开键盘,你仍然有一个未到达的目标,实体将继续移动,直到它到达目标瓷砖。我认为它看起来应该像这样:
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;
}
}