Basic Android game loop having issues
Posted
by
WillDaBeast509
on Game Development
See other posts from Game Development
or by WillDaBeast509
Published on 2013-10-20T20:43:37Z
Indexed on
2013/10/20
22:12 UTC
Read the original article
Hit count: 172
I've set up a very basic game loop that should draw a circle, run 100 times, then draw another. I also have a text field that should display how many times the loop has ran. However, the screen seems to not update. It displays a different value for the tick count (different each time the app is ran) and simply stays there. After exiting the app, I get an error saying "Unfortunately, MyApp has stopped." Here is the relevant code:
DrawView
public class DrawView extends SurfaceView implements SurfaceHolder.Callback
{
Paint p = new Paint();
MainThread thread;
private int y=0;
public DrawView(Context c)
{
super(c);
thread = new MainThread(this, getHolder());
thread.running = true;
getHolder().addCallback(this);
setFocusable(true);
}
public void draw(Canvas c)
{
if(c==null)
return;
//super.onDraw(c);
c.drawColor(Color.WHITE);
p.setColor(Color.RED);
p.setTextSize(32);
p.setTypeface(Typeface.SANS_SERIF);
c.drawCircle(getWidth()/2-100,getHeight()/2, 50, p);
c.drawText("y = " + y, 50, 50, p);
if(y>=100)
{
Log.i("DRAW", "drawing circle");
c.drawCircle(getWidth()/2+100,getHeight()/2, 50, p);
}
else
y++;
Log.i("INFO", "y = " + y);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
return true;
}
public void onDraw(Canvas c){}
public void surfaceCreated(SurfaceHolder p1)
{
thread.start();
}
public void surfaceChanged(SurfaceHolder p1, int p2, int p3, int p4)
{
// TODO: Implement this method
}
public void surfaceDestroyed(SurfaceHolder p1)
{
thread.running = false;
boolean retry = true;
while (retry)
{
try
{
thread.join();
retry = false;
}
catch (InterruptedException e)
{
Log.i("EX", "cathing exception");
}
}
}
}
MainThread
public class MainThread extends Thread
{
private DrawView page;
private SurfaceHolder holder;
public boolean running;
public MainThread(DrawView p, SurfaceHolder h)
{
super();
page = p;
holder = h;
}
@Override
public void run()
{
while(running)
{
Canvas c = holder.lockCanvas();
page.draw(c);
holder.unlockCanvasAndPost(c);
}
}
}
Here is an example log outupt: http://pastebin.com/tM9dUPuk
It counts the number of ticks correctly and should draw the second circle, but the screen looks like its not updating. After closing the app, the log continues to run and keep outputting "y = 100 drawing circle" until it crashes and shows the error report. What is going on and how can I fix these two problems?
© Game Development or respective owner