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

时间:2015-10-24 18:38:14

标签: android libgdx touch drag touchpad

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

  • 如果刚刚触摸屏幕,则精灵不应移动。
  • 精灵应根据用户将手指从初始触摸点移动的距离以不同的速度移动。
  • 一旦用户拖动了他们的 手指在一定半径之外,精灵将继续在a处移动 恒速。

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

1 个答案:

答案 0 :(得分:4)

基本上你在评论中得到了答案。

  1. 使用InputProcessor
  2. 触摸时保存触摸位置
  3. 检查保存的触摸位置与触摸拖动时的当前触摸位置之间的距离
  4. 一些小代码作为示例:

    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类的来源,看看它是如何完成的。