2012-08-01 2 views
1

안녕하세요 저는 기본 게임을 만들고 내 코드로 MVC 패턴을 구현하려고합니다. 나는 현재 가지고 있습니다 : 모델 게임 개체, 구름, 보트 물 요법.MVC 레이아웃으로 게임 상태를 구현합니까?

세계 이 함께 모든 모델을 묶어 객체

WorldRenderer 이 객체

에 모든 텍스처를 적용을 정의 GameScreen 이 사용자 입력, 터치하거나 키보드를 처리합니다.

내 문제는 어떻게 그리고 어디에서 게임 상태를 구현할 것입니까? GameScreen에 들어갈 것이라고 가정하지만 준비 상태, 실행 중, 일시 중지됨, NEXT_LVL, GAME_OVER,

상태를 구현했습니다. 그러나 준비 상태가 표시 될 때 그 상태를 알 수 있습니다. 게임이 백그라운드에서 실행 중입니까?

월드 렌더러에 정의되어 있습니다. 예를 들어, 물이 배경에서 화면 위로 올라오고 있지만, 게임 상태가 달리기로 전환 될 때만 발생하고 싶습니다.

Gamstate가 실행 상태로 전환 될 때 어떻게 Gamestate가 WorldRenderer를 초기화 할 수 있습니까? 문 renderer.render();을 RUNNING 문에 적용했지만 READY 상태로 계속 실행됩니다.

정말 도움이 될 것입니다.

건배

다니엘.

내가 WorldRenderer를 부착하고, 세계 및 GameScreen 클래스

GameScreen Class 


    import com.badlogic.gdx.Gdx; 

    import com.badlogic.gdx.Input.Keys; 

    import com.badlogic.gdx.Screen; 
    import com.badlogic.gdx.graphics.GL10; 
    import com.badlogic.gdx.graphics.OrthographicCamera; 
    import com.badlogic.gdx.graphics.Texture; 
    import com.badlogic.gdx.graphics.Texture.TextureFilter; 
    import com.badlogic.gdx.graphics.g2d.SpriteBatch; 
    import com.badlogic.gdx.graphics.g2d.TextureRegion; 

    import com.badlogic.gdx.math.Rectangle; 
    import com.badlogic.gdx.math.Vector3; 




    public class GameScreen implements Screen { 

    enum State{ 
     READY,RUNNING,PAUSED,LEVEL_END,GAME_OVER 
    } 


    MainThing game; 


    OrthographicCamera cam; 
    SpriteBatch batch; 

    Texture pauseMenu; 
    TextureRegion pauseMenuR; 

    Texture pauseBtn; 

    Texture ready; 
    TextureRegion readyR; 

    private World world; 
    private WorldRenderer renderer; 

    public static State state = State.READY; 


    public GameScreen(MainThing game){ 

     this.game = game; 
     cam = new OrthographicCamera(800,480); 
     cam.position.set(800/2, 480/2, 0); 
     batch = new SpriteBatch(); 
     state = State.READY; 

     loadingTexture(); 

    } 





    private void loadingTexture() { 

     pauseBtn = Assets.manager.get("pause.png", Texture.class); 

     pauseMenu = Assets.manager.get("resume-quit.png", Texture.class); 
     pauseMenu.setFilter(TextureFilter.Linear, TextureFilter.Linear); 
     pauseMenuR = new TextureRegion(pauseMenu,0,0,375,256); 

     ready = Assets.manager.get("ready.png",Texture.class); 
     readyR = new TextureRegion(ready,0,0,256,105); 
    } 


    public static void setState(State newState){ 
     state = newState; 
    } 





    private void update(float delta) { 

     switch (state) { 
     case READY: 
      updateReady(); 
      break; 
     case RUNNING: 
      updateRunning(delta); 
      break; 
     case PAUSED: 
      updatePaused(); 
      break; 
     case LEVEL_END: 
      updateLevelEnd(); 
      break; 
     case GAME_OVER: 
      updateGameOver(); 
      break; 
     } 

    } 



    private void updateReady() { 
     if (Gdx.input.justTouched()) { 
      state = State.RUNNING; 
     } 

    } 

    private void updateRunning(float delta) { 

     if(Gdx.input.isTouched()) { 
      Vector3 touchPos = new Vector3(); 
      touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); 
      WorldRenderer.cam.unproject(touchPos); 
      Boat.position.x = touchPos.x - 1f/2; 
      } 



     if(Gdx.input.isKeyPressed(Keys.LEFT)) { 

     Boat.velocity.x = -Boat.SPEED * delta; 
     } 


     else if(Gdx.input.isKeyPressed(Keys.RIGHT)) { 

      Boat.velocity.x = Boat.SPEED * delta; 
      } 
     else if(!Gdx.input.isKeyPressed(Keys.LEFT) && !(Gdx.input.isKeyPressed(Keys.RIGHT)) || (Gdx.input.isKeyPressed(Keys.LEFT) && (Gdx.input.isKeyPressed(Keys.RIGHT)))) { 

      Boat.velocity.x = 0; 
      } 

      Boat.update(delta); 

      if(Boat.position.x < 0) Boat.position.x = 0; 
      if(Boat.position.x > WorldRenderer.cam.viewportWidth - 1f) Boat.position.x = WorldRenderer.cam.viewportWidth - 1f; 


    } 




    private void updatePaused() { 
     // TODO Auto-generated method stub 

    } 





    private void updateLevelEnd() { 
     // TODO Auto-generated method stub 

    } 





    private void updateGameOver() { 
     // TODO Auto-generated method stub 

    } 





    private void draw(float deltaTime) { 

     Gdx.gl.glClearColor(1, 1, 1, 1); 
     Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); 
     renderer.render(deltaTime); 
     cam.update(); 
     batch.setProjectionMatrix(cam.combined); 
     batch.begin(); 

     switch (state) { 
     case READY: 
      presentReady(); 
      break; 
     case RUNNING: 
      presentRunning(deltaTime); 
      break; 
     case PAUSED: 
      presentPaused(); 
      break; 
     case LEVEL_END: 
      presentLevelEnd(); 
      break; 
     case GAME_OVER: 
      presentGameOver(); 
      break; 
     } 
     batch.end(); 
    } 




    private void presentReady() { 
     batch.draw(readyR, cam.viewportWidth /2 - 375 /2 , cam.viewportHeight /2 - 256 /2,375,256); 

    } 





    private void presentRunning(float delta) { 
     // TODO Auto-generated method stub 

    } 





    private void presentPaused() { 
     // TODO Auto-generated method stub 

    } 





    private void presentLevelEnd() { 
     // TODO Auto-generated method stub 

    } 





    private void presentGameOver() { 
     // TODO Auto-generated method stub 

    } 




    @Override 
    public void render(float delta) { 

     update(delta); 
     draw(delta); 



    } 






    @Override 
    public void resize(int width, int height) { 
     renderer.setSize(width,height); 

    } 

    @Override 
    public void show() { 
     world = new World(); 
     renderer = new WorldRenderer(world, false); 


    } 

    @Override 
    public void hide() { 


    } 

    @Override 
    public void pause() { 
     dispose(); 

    } 

    @Override 
    public void resume() { 


    } 

    @Override 
    public void dispose() { 
     Assets.unload(); 


     Boat.dispose(); 
     Cloud.dispose(); 
     WorldRenderer.dispose(); 


    } 



} 

월드 클래스

package com.inspirednotion.thing; 

import com.badlogic.gdx.math.MathUtils; 

import com.badlogic.gdx.math.Vector2; 
import com.badlogic.gdx.utils.Array; 
import com.badlogic.gdx.utils.TimeUtils; 



public class World { 

Boat boat; 
Water water; 
Cloud cloud; 
long lastDropTime; 
Array<Rain> raindrops = new Array<Rain>(); 


public Array<Rain> getRain(){ 
    return raindrops; 

} 

Boat getBoat(){ 
    return boat; 
} 
public Water getWater(){ 
    return water; 
} 

public Cloud getCloud(){ 
    return cloud; 
} 


public World(){ 

    createWorld(); 
    spawnRaindrop(); 
    lastDropTime = TimeUtils.nanoTime(); 
} 

private void createWorld() { 
    boat = new Boat(new Vector2(WorldRenderer.CAMERA_WIDTH/2 - Boat.BOAT_WIDTH/2, Water.position.y +11.3f)); 
    cloud = new Cloud(new Vector2(WorldRenderer.CAMERA_WIDTH/2 - Cloud.CLOUD_WIDTH /2, 8)); 
    water = new Water(new Vector2(WorldRenderer.CAMERA_WIDTH /2 - Water.WATER_WIDTH/2, -11.3f)); 




} 
void spawnRaindrop(){ 
raindrops.add(new Rain(new Vector2(MathUtils.random(cloud.position.x, cloud.position.x + Cloud.CLOUD_WIDTH),cloud.position.y))); 
lastDropTime = TimeUtils.nanoTime(); 
} 

public static void dispose() { 


} 
} 

WorldRenderer 클래스

public class WorldRenderer { 

    private static World world; 
    public static OrthographicCamera cam; 

    ShapeRenderer debugRenderer = new ShapeRenderer(); 

    static final float CAMERA_WIDTH = 20f; 
    static final float CAMERA_HEIGHT = 12f; 

    static Texture cloudTexture; 
    private TextureRegion cR; 
    static Texture boatAniTex; 
    TextureRegion[]     boatFrames; 
    Animation      boatAnimation; 
    TextureRegion     boatCurrentFrame; 
    static TextureRegion     currentFrameBoat; 
    TextureRegion[][]    tmpBoat; 

    static Texture cloudBg; 
    private TextureRegion cloudBgR; 


    static Texture rainDrop; 
    long lastDropTime; 
    float lastDropT; 


    private static Texture water; 
    TextureRegion[]     waveFrames; 
    Animation      waveAnimation; 
    TextureRegion     currentFrame; 
    TextureRegion     currentFrameWav; 
    TextureRegion[][]    tmp; 

    float stateTime = 0f; 

    private static SpriteBatch batch; 

    static int width; 
    static int height; 

    public void setSize(int w, int h){ 
     WorldRenderer.width= w; 
     WorldRenderer.height = h; 
    } 



    public WorldRenderer(World world, boolean debug){ 

     WorldRenderer.world = world; 
     WorldRenderer.cam = new OrthographicCamera(CAMERA_WIDTH ,CAMERA_HEIGHT); 
     WorldRenderer.cam.position.set(CAMERA_WIDTH /2f, CAMERA_HEIGHT /2f, 0); 
     WorldRenderer.cam.update(); 
     batch = new SpriteBatch(); 
     loadTextures(); 
     loadAnimations(); 




    } 





    public void loadTextures(){ 
     boatAniTex = Assets.manager.get("bin.png", Texture.class); 
     boatAniTex.setFilter(TextureFilter.Linear, TextureFilter.Linear); 
     cloudTexture = Assets.manager.get("cloud.png", Texture.class); 
     cloudTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear); 
     cR = new TextureRegion(cloudTexture,0,0,256,140); 
     cloudBg = Assets.manager.get("cloudbg.png", Texture.class); 
     cloudBg.setFilter(TextureFilter.Linear, TextureFilter.Linear); 
     cloudBgR = new TextureRegion(cloudBg,0,0,800,480); 
     water = Assets.manager.get("wavey.png", Texture.class); 
     water.setFilter(TextureFilter.Linear, TextureFilter.Linear); 
     rainDrop = new Texture(Gdx.files.internal("RainDrop_sml.png")); 
    } 


    private void loadAnimations() { 

     water.setFilter(TextureFilter.Linear, TextureFilter.Linear); 

     tmp = new TextureRegion(water).split(800,480);         
     waveFrames = new TextureRegion[14]; 
     for (int x = 0, index = 0; x < 7; x++) { 
      for (int y = 0; y < 2; y++, index++) { 
       waveFrames[index] = tmp[x][y]; 
      } 
     } 

     waveAnimation = new Animation(0.14f, waveFrames); 

     //************************ 

boatAniTex.setFilter(TextureFilter.Linear, TextureFilter.Linear); 

     tmpBoat = new TextureRegion(boatAniTex).split(64,64);         
     boatFrames = new TextureRegion[7]; 
     for (int x = 0, indexed = 0; x < 1; x++) { 
      for (int y = 0; y < 7; y++, indexed++) { 
       boatFrames[indexed] = tmpBoat[x][y]; 
      } 
     } 

     boatAnimation = new Animation(0.2f, boatFrames); 

    } 


    public void render(float delta){ 
     Gdx.gl.glClearColor(0, 0, 0, 1); 
     Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); 
     batch.setProjectionMatrix(cam.combined); 
     stateTime += Gdx.graphics.getDeltaTime(); 
     currentFrameWav = waveAnimation.getKeyFrame(stateTime += delta, true); 
     currentFrameBoat = boatAnimation.getKeyFrame(stateTime += delta, true); 
     batch.begin(); 


     batch.disableBlending(); 
     drawBackGround(); 
     batch.enableBlending(); 
     drawBoat(); 

     drawWater(delta); 
     drawCloud(); 


     batch.end(); 
     drawRain(); 
    } 





    private void drawRain() { 
     batch.begin(); 
     for( Rain bounds: world.raindrops) { 
      batch.draw(rainDrop, bounds.position.x , bounds.position.y,.2f,.2f); 

     } 
     batch.end(); 
     if(TimeUtils.nanoTime() - world.lastDropTime > 500000000) world.spawnRaindrop(); 




     Iterator<Rain> iter = world.raindrops.iterator(); 
      while(iter.hasNext()) { 
      Rain raindrop = iter.next(); 
      raindrop.position.y -=2f * Gdx.graphics.getDeltaTime(); 
      if(raindrop.position.y < Water.position.y ) { 
       System.out.println("water is hit"); 
       iter.remove(); 
      } 
      } 
    } 



    private void drawWater(float delta) { 
     batch.draw(currentFrameWav, Water.position.x , Water.position.y ,Water.WATER_WIDTH , Water.WATER_HEIGHT); 
     if (Water.position.y < -4f){ 
      Water.position.y += .1 * Gdx.graphics.getDeltaTime(); 
      Boat.position.y += .1 * Gdx.graphics.getDeltaTime(); 
     } 
    } 



    private void drawBackGround() { 

     batch.draw(cloudBgR, 0,0,CAMERA_WIDTH,CAMERA_HEIGHT); 

    } 



    private void drawCloud(){ 
     Cloud cloud = world.getCloud(); 
     batch.draw(cR,cloud.position.x ,cloud.position.y ,Cloud.CLOUD_WIDTH , Cloud.CLOUD_HEIGHT); 
    } 


    private void drawBoat(){ 
     world.getBoat(); 
     batch.draw(currentFrameBoat, Boat.position.x , Water.position.y +11.3f,Boat.BOAT_WIDTH , Boat.BOAT_HEIGHT); 
    } 








    private void drawDebug(){ 
     debugRenderer.setProjectionMatrix(cam.combined); 
     debugRenderer.begin(ShapeType.Rectangle); 

     Cloud cloud = world.getCloud(); 
     Rectangle rect = cloud.bounds; 
     float x1 = cloud.position.x + rect.x; 
     float y1 = cloud.position.y + rect.y; 
     debugRenderer.setColor(new Color(1,0,0,1)); 
     debugRenderer.rect(x1, y1, rect.width, rect.height); 

     Boat boat = world.getBoat(); 
     Rectangle rec = boat.bounds; 
     float xx1 = Boat.position.x + rec.x; 
     float yx1 = Boat.position.y + rec.y; 
     debugRenderer.setColor(new Color(1,1,0,1)); 
     debugRenderer.rect(xx1, yx1, rec.width, rec.height); 

     debugRenderer.end(); 
    } 




public static void dispose(){ 
    cloudTexture.dispose(); 
    water.dispose(); 
    boatAniTex.dispose(); 
    rainDrop.dispose(); 
    cloudBg.dispose(); 
    batch.dispose(); 

} 
} 

의 과정에서 .. 지저분한 코드를 용서하십시오 문제 해결 및 디버깅 ..

답변

2

하단 라인업 : 귀하의 GameScreenREADY 주에 있지만 귀하의 WorldRenderer은 그 사실을 알지 못해 즐거운 시간을 보냅니다. WorldRendererGameScreen 주에 연결된 상태가 있는지 확인해야합니다.

renderer.render(deltaTime)으로 전화하면 GameScreen.draw()으로 전화가 왔습니다. 상태에 관계없이 항상 위치의 업데이트는 GameScreen입니다.원하는 효과를 가정

게임이 백그라운드에서 그린 것입니다,하지만 지키기가 시작되지 -

  1. 는이 열거의 필드와, 적어도 WAITINGPLAYING입니다 WorldRenderer에 상태 열거 추가 유형. GameScreen에서이 값을 설정할 수있는 WorldRenderer에 공개 메소드가 있는지 확인하십시오.
  2. GameScreenWorldRenderer 인 경우 전화를 걸어 WorldRenderer 상태를 WAITING으로 설정해야합니다.
  3. GameScreen이 재생 중 상태로 전환되면 WorldRenderer 상태를 호출하여 PLAYING으로 설정하십시오.
  4. WorldRenderer에는 WAITING 상태, PLAYING 상태 및 둘 다에서 수행해야 할 작업을 신중히 정의하십시오. 이 경우에는 물이 뜨지 않기를 바랍니다. 그러므로 WAITING 상태 인 경우 물과 보트의 높이를 변경하지 마십시오.
관련 문제