我不知道这是否是最好的方法,但一种解决方案可能是这样的:
1.添加一个常量,让您知道您将允许同时移动多少个对象:
private static final int MAX_TOUCHES = 4;
2。添加一个固定大小的集合,这样您就可以管理当前可能移动的所有精灵:
private final Array<Sprite> sprites = new Array<Sprite>(MAX_TOUCHES);
3.现在,在您处理触摸的类中,实现touchDown()、touchDragged() 和touchUp():
/**
* In the touchDown, add the sprite being touched
**/
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// Just allow 4 sprites to move at same time
if(pointer >= MAX_TOUCHES) return true;
// Get the sprite at this current position...
Sprite sprite = getSpriteAtThisPosition(screenX, screenY);
// If sprite found, add to list with current pointer, else, do nothing
if(sprite != null) {
sprites.set(pointer, sprite);
}
return true;
}
getSpriteAtThisPosition() 只是一个返回该位置的第一个当前精灵的方法,可以返回null。
/**
* In the touchDragged, move this sprite
**/
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// Just allow 4 sprites to move at same time
if(pointer >= MAX_TOUCHES) return false;
// Get the sprite with the current pointer
Sprite sprite = sprites.get(pointer);
// if sprite is null, do nothing
if(sprite == null) return false;
// else, move sprite to new position
sprite.setPosition(screenX - sprite.getWidth() / 2,
Gdx.graphics.getHeight() - screenY -
sprite.getHeight() / 2);
return false;
}
/**
* In the touchUp, remove this sprite from the list
**/
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// Just allow 4 sprites to move at same time
if(pointer >= MAX_TOUCHES) return true;
// remove sprite at pointer position
sprites.set(pointer, null);
return true;
}