Libgdx 触摸屏幕上的任何位置以移动精灵。

3

目前我正在使用scene2d触摸板在屏幕上移动一个精灵。我想做的是能够使用整个屏幕作为触摸板来移动精灵,但不知道从哪里开始。

  • 如果只是触摸屏幕,则精灵不应该移动。
  • 根据用户从初始触点移动手指的距离,精灵应该以不同的速度移动。
  • 一旦用户将手指拖出一定半径,精灵就会以恒定速度继续移动。

基本上它是一个没有实际使用scene2d触摸板的触摸板。


你需要自己实现一个定制的 InputProcessor 来完成这个任务。也许 GestureDetector 可以帮助你,但是在 libgdx 中没有任何可以完成这个任务的东西。我怀疑有人会为你编写这个代码。 - noone
我并不是在请求有人为我编写代码,只是想寻求建议或者向那些曾经尝试过的人请教一下从哪里开始或者需要注意什么。 - Steve Fitzsimons
1个回答

4

基本上你可以在评论中找到答案。

  1. 使用InputProcessor
  2. 在接触时保存触摸位置
  3. 检查在拖动过程中保存的触摸位置和当前触摸位置之间的距离

这里有一些示例代码:

class MyInputProcessor extends InputAdapter
{
    private Vector2 touchPos    = new Vector2();
    private Vector2 dragPos     = new Vector2();
    private float   radius      = 200f;

    @Override
    public boolean touchDown(
            int screenX,
            int screenY,
            int pointer,
            int button)
    {
        touchPos.set(screenX, Gdx.graphics.getHeight() - screenY);

        return true;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer)
    {
        dragPos.set(screenX, Gdx.graphics.getHeight() - screenY);
        float distance = touchPos.dst(dragPos);

        if (distance <= radius)
        {
            // gives you a 'natural' angle
            float angle =
                    MathUtils.atan2(
                            touchPos.x - dragPos.x, dragPos.y - touchPos.y)
                            * MathUtils.radiansToDegrees + 90;
            if (angle < 0)
                angle += 360;
            // move according to distance and angle
        } else
        {
            // keep moving at constant speed
        }
        return true;
    }
}

最后,您始终可以查看libgdx类的源代码,以了解其如何实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接