Search code examples
android2dsleepframe-ratethread-sleep

Android Development: Thread.sleep just slow down game


I have a:

@Override
    public boolean onTouchEvent(MotionEvent event) {
        synchronized (event)  
        {  

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

        if(event.getAction() == MotionEvent.ACTION_DOWN){

          isDown = true;
        }else if(event.getAction() == MotionEvent.ACTION_MOVE){

          isDown = true;
        }else if(event.getAction() == MotionEvent.ACTION_UP){

         isDown = false;
        }

        return true;
        } 

    }

Then in my MainGame thread I use setCharacterPosition();

 public void setCharacterPosition(){
    if(isDown){
CharacterX += 32;
}
    }

but this make my Character to run toooo quickly so i tried to add:

Thread.sleep(500);

Because i only want my character to increase with 32 every half a sencond.

IT works but bring my FPS down to 2-3.

How do i do it right?

//Simon


Solution

  • I know little about Java or Android, but this seems like a wrong way to do it.

    What you're after is setting up a Game Loop (a loop that continuously runs and updates the game logic, frame by frame).

    This loop is executed on timed intervals (usually 60 frames per second, or maybe less on a mobile platform).

    On each frame, you can scale the game object's movements based on the time elapsed since last frame.

    This gives a scaled movement, irrelevant to the clock speed of the device you're using.

    Read more abot game loops in these fine resources:

    Simple Java Android Game Loop

    Game Loop

    Android Game Loop