我正在LibGDX中制作Android游戏,其中玩家对象将相应地移动到触摸Y位置并且运动平稳,使其看起来像是在跟随触摸移动。到目前为止,这是我的代码,它应该如此,但它不够平滑,有时它在到达触摸位置时“摆动”(它没有到达零距离,但绕过它。):
if ((player.getPosition().y * world.ppuY) < (world.height-touch.y-(world.ppuY/2f))) { //if player is below touch
if (Math.abs((player.getPosition().y * world.ppuY)-(world.height-touch.y-(world.ppuY/2f))) > 20) { // if distance is more than 20
player.getVelocity().y = Math.min(
Math.abs(
((player.getPosition().y * world.ppuY)-(world.height-touch.y-(world.ppuY/2f)))/2f),
Player.SPEED); // set velocity
} else { // if distance is less than 20
if (player.getVelocity().y != 0)
player.getVelocity().y *= 0.3f+delta; // slow down velocity
else
player.getVelocity().y = Math.min(
Math.abs(
((player.getPosition().y * world.ppuY)-(world.height-touch.y-(world.ppuY/2f)))/2f),
Player.SPEED); // just so it follows even when the touch moves slightly
}
}
if ((player.getPosition().y * world.ppuY) > (world.height-touch.y-(world.ppuY/2f))) {
if (Math.abs((player.getPosition().y * world.ppuY)-(world.height-touch.y-(world.ppuY/2f))) > 20) {
player.getVelocity().y = -Math.min(
Math.abs(
((player.getPosition().y * world.ppuY)-(world.height-touch.y-(world.ppuY/2f)))/2f),
Player.SPEED);
} else {
if (player.getVelocity().y > 1) {
player.getVelocity().y *= 0.3f+delta;
} else {
player.getVelocity().y = -Math.min(
Math.abs(
((player.getPosition().y * world.ppuY)-(world.height-touch.y-(world.ppuY/2f)))/2f),
Player.SPEED);
}
}
}
有没有比这更好的方法,首先使代码更短,其次使平滑运动更好,更稳定?
答案 0 :(得分:3)
创建smoth运动的一种好方法是使用spec值将旧位置插入到新位置。根据值,相机或图形会移动更多的smoth或更少的smoth。为此,您需要将setY()
更改为以下内容:
currentpos.y = Interpolation.linear.apply(currentpos.y, gotopos.y, value[0,1]);
currentpos.x = Interpolation.linear.apply(currentpos.x, gotopos.x, value[0,1]);
根据值,它会将当前位置插入到goto位置。它对于装载栏或救生棒等也很有用,它们不会“跳”到新值。
使用value[0,1]
来寻找合适的动作速度。