我有一个演员,我想用触摸拖动。
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)
有什么想法吗?谢谢你的期待!
答案 0 :(得分:3)
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) );
}
});