在 libGDX InputProcessor 的 touchDown() 中,我正在开发一种方法来为每个屏幕触摸创建一个新的 TouchPoint 矩形对象。
我尝试将可创建的 TouchPoint 矩形的最大数量限制为两个;我只需要使用两次屏幕触摸即可。每个唯一对象都应在 touchDragged() 中更新为其新的屏幕触摸位置,然后在 touchUp() 中删除。
我已经成功地能够为单次触摸创建所需的结果,但不能为多次屏幕触摸创建所需的结果。对于第二次并发触摸,TouchPoint 矩形对象从第一次触摸消失,然后显示在第二次触摸位置。在第二次触摸的 touchUp() 时,对象重新出现在第一次触摸的触摸位置。
- 哪段代码逻辑包含错误?
我如何解决它?
/*experiment*/ public Vector3 tps[] = new Vector3[2]; /*experiment*/ @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { /*experiment*/ if(pointer < 2){ if(pointer == 0) { Vector3 touchPosition1 = new Vector3(); tps[pointer] = touchPosition1; tps[pointer].set(screenX, screenY, 0); gameScreen.getWorldRenderer().getCamera().unproject(tps[pointer]); touchPoint1 = new TouchPoint(52, 52, new Vector2(tps[pointer].x - 26, tps[pointer].y - 26)); gameScreen.getWorld().getTouchPoints().add(touchPoint1); Gdx.app.log("TOUCH DOWN", "pointer: " + pointer + " x: " + tps[pointer].x + " y: " + tps[pointer].y); } if(pointer == 1) { Vector3 touchPosition2 = new Vector3(); tps[pointer] = touchPosition2; tps[pointer].set(screenX, screenY, 0); gameScreen.getWorldRenderer().getCamera().unproject(tps[pointer]); touchPoint2 = new TouchPoint(52, 52, new Vector2(tps[pointer].x - 26, tps[pointer].y - 26)); gameScreen.getWorld().getTouchPoints().add(touchPoint2); Gdx.app.log("TOUCH DOWN", "pointer: " + pointer + " x: " + tps[pointer].x + " y: " + tps[pointer].y); } } return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { /*experiment*/ gameScreen.getWorld().getTouchPoints().removeIndex(pointer); //note: dispose of unused vector3 objects //note: dispose of all other unused objects /*experiment*/ return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { /*experiment*/ tps[pointer].set(screenX, screenY, 0); gameScreen.getWorldRenderer().getCamera().unproject(tps[pointer]); for(TouchPoint tp: gameScreen.getWorld().getTouchPoints()) { tp.moveRectangleToPosition(new Vector2(tps[pointer].x - 26, tps[pointer].y - 26)); tp.updateRectangleBoundaries(); } Gdx.app.log("TOUCH DRAGGING", "pointer: " + pointer + " x: " + tps[pointer].x + " y: " + tps[pointer].y); /*experiment*/ }
此外,如果发生第三次屏幕触摸,程序会崩溃。
日志猫:
08-27 14:08:31.808: W/dalvikvm(9988): threadid=11: thread exiting with uncaught exception (group=0x41711438)
08-27 14:08:31.808: E/AndroidRuntime(9988): FATAL EXCEPTION: GLThread 40874
08-27 14:08:31.808: E/AndroidRuntime(9988): java.lang.IndexOutOfBoundsException: 2
08-27 14:08:31.808: E/AndroidRuntime(9988): at com.badlogic.gdx.utils.Array.removeIndex(Array.java:229)
08-27 14:08:31.808: E/AndroidRuntime(9988): at com.manytouches.controller.InputHandler.touchUp(InputHandler.java:104)
谢谢你的时间。