Using a thread as a GameLoop

2019-08-28 18:55发布

What I need to do is have a loop that I can stop if I want... I made a new thread and named it GameLoop I want this to do all of my bitmap X and Y changes but when I tryed to run what I have nothing moves, It just sends me a picture. Heres my code, what did I do wrong?

 public GamePage(Context context, AttributeSet attrs) 
    {
        super(context, attrs);
            //other code here
            Thread gameThread = new Thread(new GameLoop());
            gameThread.start();  
    }

public class GameLoop implements Runnable
{
    public void run()
    {
        try {
            Thread.sleep(speed);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.d("LoopRunning", "The Game Loop Is Running!");

        switch ((int)possition)
        {
        case 0:
            if (counter < 110) {SunY --; counter++;}
            if (counter >= 110 && counter < 240) {SunY --; SunX ++; counter++;} 
            if (counter >= 240 && counter < 360) {SunY -= 0.5; SunX ++; counter++;}
            if (counter >= 360 && counter < 662) {SunY -= 0.333; SunX ++; counter++;}
            if (counter >= 662 && counter < 1004) {SunY += 0.333; SunX++; counter++;}
            if (counter >= 1004 && counter < 1104) {SunY += 0.5; SunX++; counter++;}
            if (counter >= 1104 && counter < 1224) {SunY ++; SunX++; counter++;}
            if (counter >= 1224 && counter < 1345) {SunY ++; counter++;}
            break;

        case 1:
            if (ZombieX < canvasWidth/2 + 300) ZombieX += 10;

            if (counter2 < 110) {MoonY --; counter2++;}
            if (counter2 >= 110 && counter2 < 240) {MoonY --; MoonX ++; counter2++;} 
            if (counter2 >= 240 && counter2 < 360) {MoonY -= 0.5; MoonX ++; counter2++;}
            if (counter2 >= 360 && counter2 < 662) {MoonY -= 0.333; MoonX ++; counter2++;}
            if (counter2 >= 662 && counter2 < 1004) {MoonY += 0.333; MoonX++; counter2++;}
            if (counter2 >= 1004 && counter2 < 1104) {MoonY += 0.5; MoonX++; counter2++;}
            if (counter2 >= 1104 && counter2 < 1224) {MoonY ++; MoonX++; counter2++;}
            if (counter2 >= 1224 && counter2 < 1345) {MoonY ++; counter2++;}
            break;
        }
    }
}

1条回答
甜甜的少女心
2楼-- · 2019-08-28 19:18

Use two nested while loops as so:

@Override public void run() {
    while (gameShouldRun) {
        while (iterateGame) {
            // do game stuff
        }
    }
}

Also, run is not looped by default. If you want the game to loop until stopped, you will need a while loop in the run method.

查看更多
登录 后发表回答