You are new to this series? Please start with the first part.
The sixth part of this series will let you move the item you will add. As long as you touch the screen, you can change the position of the bitmap you want to add.
We simply have to add a temporary class variable in our Panel class.
1 | private GraphicObject _currentGraphic = null; |
Modify our onTouchEvent() to behave differently for different motion events.
On ACTION_DOWN we will add a new GraphicObject to our temporary variable with the coordinates of the touch event.
On ACTION_MOVE we will change the coordinates of this temporary bitmap following our movement on the screen.
On ACTION_DOWN we will finally add the temporary bitmap to our ArrayList and null the currentGraphic variable.
We have no check for NullPointerExceptions because the order of the motion events is unchangeable. It should never happen that a ACTION_MOVE is triggered without an ACTION_DOWN triggered before. The same with ACTION_UP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @Override public boolean onTouchEvent(MotionEvent event) { synchronized (_thread.getSurfaceHolder()) { GraphicObject graphic = null; if (event.getAction() == MotionEvent.ACTION_DOWN) { graphic = new GraphicObject(BitmapFactory.decodeResource(getResources(), R.drawable.icon)); graphic.getCoordinates().setX((int) event.getX() - graphic.getGraphic().getWidth() / 2); graphic.getCoordinates().setY((int) event.getY() - graphic.getGraphic().getHeight() / 2); _currentGraphic = graphic; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { _currentGraphic.getCoordinates().setX((int) event.getX() - _currentGraphic.getGraphic().getWidth() / 2); _currentGraphic.getCoordinates().setY((int) event.getY() - _currentGraphic.getGraphic().getHeight() / 2); } else if (event.getAction() == MotionEvent.ACTION_UP) { _graphics.add(_currentGraphic); _currentGraphic = null; } return true; } } |
Our onDraw() just draw what is added to the ArrayList, so we should change the method, too.
We will append a check if the _currentGraphic is null or not, if it is not null we will draw it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @Override public void onDraw(Canvas canvas) { canvas.drawColor(Color.BLACK); Bitmap bitmap; GraphicObject.Coordinates coords; for (GraphicObject graphic : _graphics) { bitmap = graphic.getGraphic(); coords = graphic.getCoordinates(); canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null); } // draw current graphic at last... if (_currentGraphic != null) { bitmap = _currentGraphic.getGraphic(); coords = _currentGraphic.getCoordinates(); canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null); } } |
Don’t append logic to updatePhysics() because we don’t want the speed already working on our _currentObject. If you do it anyway you will notice weird behavior if you long touch the screen without moving your finger.
Full code: tutorial2d-src
Comments
Leave a comment Trackback