Using a thread as a GameLoop

不想你离开。 提交于 2019-12-24 19:25:35

问题


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:


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.



来源:https://stackoverflow.com/questions/10904287/using-a-thread-as-a-gameloop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!