InputListener.touchDragged 中的鼠标坐标不一致(闪烁)

Inconsistent (flickering) mouse coordinates in InputListener.touchDragged

我有一个演员,我想通过触摸拖动来移动它。

class Tile extends Actor {
    Tile (char c) {
        addListener(new InputListener() {
            private float prevX, prevY;

            @Override
            public void touchDragged (InputEvent event, float x, float y, int pointer) {
                Gdx.app.log(TAG, "touchDrag: (" + x + "," + y);
                Tile cur = (Tile)event.getTarget();
                cur.setPosition(  //this call seems to cause the problem
                        cur.getX() + (x - prevX),
                        cur.getY() + (y - prevY) );
                prevX = x; prevY = y;
            }
        });
    }

    @Override
    public void draw(Batch batch, float alpha) {
        batch.draw(texture, getX(), getY());
    }

}

瓷砖在被拖动时会颤抖,移动速度大约是触摸速度的一半。这由日志行确认,它输出如下坐标:

I/Tile: touchDrag: (101.99991,421.99994)
I/Tile: touchDrag: (112.99985,429.99994)
I/Tile: touchDrag: (101.99991,426.99994)
I/Tile: touchDrag: (112.99985,433.99994)
I/Tile: touchDrag: (101.99991,429.99994)
I/Tile: touchDrag: (112.99985,436.99994)

如果我删除注释行(即不重置演员的位置),拖动输出看起来更合理:

I/Tile: touchDrag: (72.99997,78.99994)
I/Tile: touchDrag: (65.99997,70.99994)
I/Tile: touchDrag: (61.99997,64.99994)
I/Tile: touchDrag: (55.99997,58.99994)
I/Tile: touchDrag: (51.99997,52.99994)
I/Tile: touchDrag: (42.99997,45.99994)

有什么想法吗?感谢观看!

InputListener 方法中的坐标是相对于 Actor 的位置给出的,因此如果您同时移动 Actor,则它们无法与之前的值进行比较。

相反,存储原始位置并相对于该位置移动。数学计算结果适合您的动作:

    addListener(new InputListener() {
        private float startX, startY;

        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            startX = x;
            startY = y;
            return true;
        }

        @Override
        public void touchDragged (InputEvent event, float x, float y, int pointer) {
            Tile cur = (Tile)event.getTarget();
            cur.setPosition(
                    cur.getX() + (x - startX),
                    cur.getY() + (y - startY) );
        }
    });