Playing with graphics in Android – Part V
by Martin on May.23, 2009, under tutorial
You are new to this series? Please start with the first part.
Also be aware of a minor bug in the last series.
The fifth part of this series will let the icons move around.
What do we need, if we want to have the icons move around? Right, we need the direction of the movement and the speed. For this we need a new inner class comparable with the inner class Coordinates in our class GraphicObject.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | public class Speed { public static final int X_DIRECTION_RIGHT = 1; public static final int X_DIRECTION_LEFT = -1; public static final int Y_DIRECTION_DOWN = 1; public static final int Y_DIRECTION_UP = -1; private int _x = 1; private int _y = 1; private int _xDirection = X_DIRECTION_RIGHT; private int _yDirection = Y_DIRECTION_DOWN; /** * @return the _xDirection */ public int getXDirection() { return _xDirection; } /** * @param direction the _xDirection to set */ public void setXDirection(int direction) { _xDirection = direction; } public void toggleXDirection() { if (_xDirection == X_DIRECTION_RIGHT) { _xDirection = X_DIRECTION_LEFT; } else { _xDirection = X_DIRECTION_RIGHT; } } /** * @return the _yDirection */ public int getYDirection() { return _yDirection; } /** * @param direction the _yDirection to set */ public void setYDirection(int direction) { _yDirection = direction; } public void toggleYDirection() { if (_yDirection == Y_DIRECTION_DOWN) { _yDirection = Y_DIRECTION_UP; } else { _yDirection = Y_DIRECTION_DOWN; } } /** * @return the _x */ public int getX() { return _x; } /** * @param speed the _x to set */ public void setX(int speed) { _x = speed; } /** * @return the _y */ public int getY() { return _y; } /** * @param speed the _y to set */ public void setY(int speed) { _y = speed; } public String toString() { String xDirection; if (_xDirection == X_DIRECTION_RIGHT) { xDirection = "right"; } else { xDirection = "left"; } return "Speed: x: " + _x + " | y: " + _y + " | xDirection: " + xDirection; } } |
Now we need to make a class variable for the speed, a getter method and the initialization inside the constructor of our GraphicObject class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // code snipped private Speed _speed; public GraphicObject(Bitmap bitmap) { _bitmap = bitmap; _coordinates = new Coordinates(); _speed = new Speed(); } public Speed getSpeed() { return _speed; } // code snipped |
The next step is a new function we will call updatePhysics(). This will be a method from our Panel class.
Inside this method we will iterate over every added GraphicObject object and calculate the new position depending on speed and last position. The method will also handle the border collision with the panel borders so the icons will never have a position outside the visibility. The most things are stupid math for pixel calculation so I won’t do into details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public void updatePhysics() { GraphicObject.Coordinates coord; GraphicObject.Speed speed; for (GraphicObject graphic : _graphics) { coord = graphic.getCoordinates(); speed = graphic.getSpeed(); // Direction if (speed.getXDirection() == GraphicObject.Speed.X_DIRECTION_RIGHT) { coord.setX(coord.getX() + speed.getX()); } else { coord.setX(coord.getX() - speed.getX()); } if (speed.getYDirection() == GraphicObject.Speed.Y_DIRECTION_DOWN) { coord.setY(coord.getY() + speed.getY()); } else { coord.setY(coord.getY() - speed.getY()); } // borders for x... if (coord.getX() < 0) { speed.toggleXDirection(); coord.setX(-coord.getX()); } else if (coord.getX() + graphic.getGraphic().getWidth() > getWidth()) { speed.toggleXDirection(); coord.setX(coord.getX() + getWidth() - (coord.getX() + graphic.getGraphic().getWidth())); } // borders for y... if (coord.getY() < 0) { speed.toggleYDirection(); coord.setY(-coord.getY()); } else if (coord.getY() + graphic.getGraphic().getHeight() > getHeight()) { speed.toggleYDirection(); coord.setY(coord.getY() + getHeight() - (coord.getY() + graphic.getGraphic().getHeight())); } } } |
The last step is pretty simple: Add a method call of updatePhysics() to the run() method of our TutorialThread directly above the onDraw() call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | @Override public void run() { Canvas c; while (_run) { c = null; try { c = _surfaceHolder.lockCanvas(null); synchronized (_surfaceHolder) { _panel.updatePhysics(); _panel.onDraw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { _surfaceHolder.unlockCanvasAndPost(c); } } } } |
Finally I would like to advise you a good article about the different ways to implement a game loop.
If you want to change the speed and the direction of each icon, feel free to implement it inside the onTouchEvent() method. A possibility is to use random settings for the speed and the direction.
Full source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | package com.droidnova.android.tutorial2d; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.os.Bundle; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.Window; public class Tutorial2D extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(new Panel(this)); } class Panel extends SurfaceView implements SurfaceHolder.Callback { private TutorialThread _thread; private ArrayList<GraphicObject> _graphics = new ArrayList<GraphicObject>(); public Panel(Context context) { super(context); getHolder().addCallback(this); _thread = new TutorialThread(getHolder(), this); setFocusable(true); } @Override public boolean onTouchEvent(MotionEvent event) { synchronized (_thread.getSurfaceHolder()) { if (event.getAction() == MotionEvent.ACTION_DOWN) { GraphicObject 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); _graphics.add(graphic); } return true; } } public void updatePhysics() { GraphicObject.Coordinates coord; GraphicObject.Speed speed; for (GraphicObject graphic : _graphics) { coord = graphic.getCoordinates(); speed = graphic.getSpeed(); // Direction if (speed.getXDirection() == GraphicObject.Speed.X_DIRECTION_RIGHT) { coord.setX(coord.getX() + speed.getX()); } else { coord.setX(coord.getX() - speed.getX()); } if (speed.getYDirection() == GraphicObject.Speed.Y_DIRECTION_DOWN) { coord.setY(coord.getY() + speed.getY()); } else { coord.setY(coord.getY() - speed.getY()); } // borders for x... if (coord.getX() < 0) { speed.toggleXDirection(); coord.setX(-coord.getX()); } else if (coord.getX() + graphic.getGraphic().getWidth() > getWidth()) { speed.toggleXDirection(); coord.setX(coord.getX() + getWidth() - (coord.getX() + graphic.getGraphic().getWidth())); } // borders for y... if (coord.getY() < 0) { speed.toggleYDirection(); coord.setY(-coord.getY()); } else if (coord.getY() + graphic.getGraphic().getHeight() > getHeight()) { speed.toggleYDirection(); coord.setY(coord.getY() + getHeight() - (coord.getY() + graphic.getGraphic().getHeight())); } } } @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); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { _thread.setRunning(true); _thread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { // simply copied from sample application LunarLander: // we have to tell thread to shut down & wait for it to finish, or else // it might touch the Surface after we return and explode boolean retry = true; _thread.setRunning(false); while (retry) { try { _thread.join(); retry = false; } catch (InterruptedException e) { // we will try it again and again... } } } } class TutorialThread extends Thread { private SurfaceHolder _surfaceHolder; private Panel _panel; private boolean _run = false; public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) { _surfaceHolder = surfaceHolder; _panel = panel; } public void setRunning(boolean run) { _run = run; } public SurfaceHolder getSurfaceHolder() { return _surfaceHolder; } @Override public void run() { Canvas c; while (_run) { c = null; try { c = _surfaceHolder.lockCanvas(null); synchronized (_surfaceHolder) { _panel.updatePhysics(); _panel.onDraw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { _surfaceHolder.unlockCanvasAndPost(c); } } } } } class GraphicObject { public class Speed { public static final int X_DIRECTION_RIGHT = 1; public static final int X_DIRECTION_LEFT = -1; public static final int Y_DIRECTION_DOWN = 1; public static final int Y_DIRECTION_UP = -1; private int _x = 1; private int _y = 1; private int _xDirection = X_DIRECTION_RIGHT; private int _yDirection = Y_DIRECTION_DOWN; /** * @return the _xDirection */ public int getXDirection() { return _xDirection; } /** * @param direction the _xDirection to set */ public void setXDirection(int direction) { _xDirection = direction; } public void toggleXDirection() { if (_xDirection == X_DIRECTION_RIGHT) { _xDirection = X_DIRECTION_LEFT; } else { _xDirection = X_DIRECTION_RIGHT; } } /** * @return the _yDirection */ public int getYDirection() { return _yDirection; } /** * @param direction the _yDirection to set */ public void setYDirection(int direction) { _yDirection = direction; } public void toggleYDirection() { if (_yDirection == Y_DIRECTION_DOWN) { _yDirection = Y_DIRECTION_UP; } else { _yDirection = Y_DIRECTION_DOWN; } } /** * @return the _x */ public int getX() { return _x; } /** * @param speed the _x to set */ public void setX(int speed) { _x = speed; } /** * @return the _y */ public int getY() { return _y; } /** * @param speed the _y to set */ public void setY(int speed) { _y = speed; } public String toString() { String xDirection; if (_xDirection == X_DIRECTION_RIGHT) { xDirection = "right"; } else { xDirection = "left"; } return "Speed: x: " + _x + " | y: " + _y + " | xDirection: " + xDirection; } } /** * Contains the coordinates of the graphic. */ public class Coordinates { private int _x = 100; private int _y = 0; public int getX() { return _x + _bitmap.getWidth() / 2; } public void setX(int value) { _x = value - _bitmap.getWidth() / 2; } public int getY() { return _y + _bitmap.getHeight() / 2; } public void setY(int value) { _y = value - _bitmap.getHeight() / 2; } public String toString() { return "Coordinates: (" + _x + "/" + _y + ")"; } } private Bitmap _bitmap; private Coordinates _coordinates; private Speed _speed; public GraphicObject(Bitmap bitmap) { _bitmap = bitmap; _coordinates = new Coordinates(); _speed = new Speed(); } public Bitmap getGraphic() { return _bitmap; } public Speed getSpeed() { return _speed; } public Coordinates getCoordinates() { return _coordinates; } } } |
July 13th, 2009 on 5:44 pm
ha ha,it is very good, my icon can run on the screen.
July 20th, 2009 on 8:33 pm
well nice one and very helpful
thx for sharing (the whole tutorial)
August 10th, 2009 on 8:51 pm
awesome!!
this serials help me a lot!!
September 7th, 2009 on 5:39 am
I’ve done extensive work with main game loops and the best solution I’ve found is to implement all movement as a time-step using some sort of integrator. The basic one being Euler but for complex physics you can get into more complex ones like Verlet or RK4.
I use this method on my PocketPC engine and have tested on low and high end devices, works GREAT!
So you determine the time delta between frames, that is the number of seconds elapsed between frames and store that as a float. This value will be fX += fDeltaTime;
Want to move at 5 pixels a second?
Implementation:
This is the root of all the other updates which will happen in FrameUpdate and all rendering is done in FrameRender.
September 7th, 2009 on 6:22 am
Thats nearly the same mentioned in the game loop article I link in the post.
Thank you anyway for sharing your code
September 7th, 2009 on 3:00 pm
Actually the reason I put that up is because the game loop article didn’t really go into detail about the time-step technique and most certainly didn’t show any code snippets.
September 7th, 2009 on 4:01 pm
Are you sure you read the same article? Your implementation is just slightly different from one mentioned in the article and i see code snippets.
Anyway the way to update the game on a fixed times per second and drawing as often as possible is always the way a game loop should be implemented.
September 29th, 2009 on 8:22 pm
Hi, I’m trying to apply this page’s logic into my own application, but I have something strange and I don’t think it’s good. I verified that my _panel.updatePhysics() and _panel.onDraw(c) methods both get called, but the screen is not updated.
If I place a _panel.postInvalidate() between the two previous method calls, it does work. But this should not be necessary right? And I’m afraid it will kill the whole idea (with respect to performance) of using the surfaceholder. Do you have any idea where I should search for my mistake? Thanks for this great tutorial!
September 29th, 2009 on 8:46 pm
Do you extend SurfaceView for you panel? Do you have the SurfaceHolder.Callback implemented?
September 30th, 2009 on 7:24 am
Hi Martin, yes my Panel extends SurfaceView and implements SurfaceHolder.Callback. Panel has a ‘protected void onDraw(Canvas canvas)’ which does get called. I computed that I’m calling onDraw almost 50 times per second (in the emulator). The weird thing is, I seem to see a few updates in the beginneng, then it stops (within half a second), unless I add the _panel.postInvalidate(). Thanks.
September 30th, 2009 on 7:57 am
Where do you get your canvas from?
Maybe you can see something while debugging?
September 30th, 2009 on 5:37 pm
Ah that was a good hint. I found out 2 threads call onDraw, the main thread and the tutorial thread. They both use their own canvas (references were not equal). That explains why there were some screen updates in the beginning (the main thread calls onDraw twice). Now i have to find out why lockCanvas returns a possibly wrong canvas in my tutorialthread… thanks.
October 1st, 2009 on 7:01 pm
FOUND IT! Finally… If you’d add a ’setBackgroundColor(Color.BLACK);’ right after the super(context) call in the Panel constructor, you’ll find out it does not work anymore. If you change it into a Color.RED, you won’t see any RED though… I don’t really understand why this messes things up, but at least I got my application to work now
Thanks for your help.
February 12th, 2010 on 11:44 am
hey great tutorial again. but this time, there’s something I don’t know how it works. it is in line 71:
coord.setX(-coord.getX());
or in line 74:
coord.setX(coord.getX() + getWidth() – (coord.getX() + graphic.getGraphic().getWidth()));
I know, it protects the graphics to be set too near at the borders, but I couldn’t figure out what that code does.
Greetz
cykan