views:

101

answers:

3

I am building a 2D game with Android SurfaceView. When I touch the screen the game animation runs slowly. Why, and how can I avoid this?

The touch events are stubs just like onTouchEvents(MotionEvents ev){ empty };. All of the game logic and graphics draw code are in run() in an extends Thread class.

+1  A: 

Have you looked at the tutorials at http://www.droidnova.com ? They are good intro game tuts and ran very quickly when I did them. If they run slowly on your device with touch it is probably not a dev issue

Mark
A: 

Sleeping the UI thread for 16-20ms will keep the touch event handling code from being called too many times per second.

Example:

@Override
public boolean onTouchEvent(MotionEvent event) {

 //Event handling logic

    try {
        Thread.sleep(16);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return true;
}

Touch events are dispatched as quickly as the UI thread can read them, by sleeping the thread you are able to skip a number of event dispatches. (Though not a noticeable amount for your game logic or the user)

Frank
A: 
@Override
public void run ( )
{
    while(irunning)
    {
        while(paused)
        {
            sleep(2);
            synchronized ( holder )
            {
                    canvas = holder.lockCanvas(null);
                    //updateEvents();
                    //updatePsgstate();
                    //updateRole();
                    sortImages();
                    drawBgland();
                    drawImages();
                    drawAdminicle();
                    holder.unlockCanvasAndPost(canvas);                         
            }

        }
        sleep(10);
    }

}



@Override
public boolean dispatchTouchEvent ( MotionEvent ev )
{
    try
    {
        Thread.sleep( 32 );
    }
    catch ( InterruptedException e )
    {           
        e.printStackTrace();
    }
    synchronized ( ev )
    {
        Log.i( "T" , "onTouch" );
    }
    return true;
}


@Override
public void surfaceCreated(SurfaceHolder holder) 
{               
    mThread.start();

// if (hasFocus()) // { // return; // } // else // { // requestFocusFromTouch(); // }

}

this is base method that i used. that's my code. any problem about it ?

Scofield