android - 如何实现锁定在 Y 轴上的对象跟随鼠标位置的平滑移动?

标签 android libgdx touch game-physics

我正在 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);
                }
            }
        }

有没有比这更好的方法,一是让代码更短,二是让流畅的 Action 变得更好更稳定?

最佳答案

创建平滑移动的一个好方法是使用规范值将旧位置插值到新位置。根据值,相机或人物移动得更平滑或更不平滑。要解决此问题,您需要将 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]);

根据值,它会将当前位置插入到转到位置。它对于加载条或生命条等也很有用,因为它们不会“跳”到新值。

尝试使用值[0,1]来找到最适合您的移动速度。

关于android - 如何实现锁定在 Y 轴上的对象跟随鼠标位置的平滑移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21801599/

相关文章:

android - 为什么调用 finish() 会导致调用 onCreate() 并启动一个新的 Activity?

java - 我无法删除工具栏上的图标

android - 如何访问这个内部存储目录?

javascript - AngularJS 1.2 - 基于左滑或右滑的不同动画

touch - 移相器 : Attach Touch Event on Sprite

android - 如何解决错误 : This attribute must be localized.(在 'text' 处,值为 'TOP_LEFT')

java - 如何将位图字体添加到 libgdx 中的对话框

java - 如何沿着特定轨迹放置物体?

java - LibGDX + Box2D |相机太大

java - 具有多个 View 的 Android 触摸事件