2014-07-12 4 views
0

캐릭터의 좌표를 저장하려고하는 안드로이드 게임을 개발 중입니다. 나는 onSaveInstanceStateonRestoreInstanceState 방법을 사용하고 있습니다. 그러나 테스트했을 때 좌표가 변경되었습니다.화면이 꺼져있을 때 활동 상태 저장하기

는 그래서 올바른 값을로드하지만 그 다음 나쁜 번호를 저장 그 후이 잘못된 값을로드합니다.

클래스 1

package hu.cig.vob; 

import android.app.Activity; 
import android.graphics.drawable.Drawable; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.View.OnTouchListener; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import cug.hu.vob.R; 

public class Level extends Activity { 
    private LevelView lv; 
    private LinearLayout linearL; 
    private Button left, right, jump, fire; 
    private mListener l = new mListener(); 

    //Konstansok az activity allapotanak mentesehez 
    private String playerX = "PlayerX",playerY="PlayerY",playerH="PlayerH"; 

    @SuppressWarnings("deprecation") 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.level_layout); 

     final ImageView healthBar = (ImageView) findViewById(R.id.life_view); 

     Drawable d = getResources().getDrawable(R.drawable.main_screen_bg); 
     linearL = (LinearLayout) findViewById(R.id.linear_layout); 
     linearL.setBackgroundDrawable(d); 

     lv = new LevelView(getApplicationContext(), getIntent().getIntExtra(
       MainActivity.LEVEL_EXTRA, 0), getWindowManager()); 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.FILL_PARENT, 
       LinearLayout.LayoutParams.FILL_PARENT); 
     lv.setLayoutParams(params); 
     linearL.addView(lv, 0); 

     left = (Button) findViewById(R.id.left); 
     right = (Button) findViewById(R.id.right); 
     jump = (Button) findViewById(R.id.jump); 
     fire = (Button) findViewById(R.id.fire); 

     left.setOnTouchListener(l); 
     right.setOnTouchListener(l); 
     jump.setOnTouchListener(l); 
     fire.setOnTouchListener(l); 

     lv.setOnClickListener(new OnClickListener() { 
//  Game over screen esetén kilép 
      @Override 
      public void onClick(View v) { 
       if (lv.getGameState()) { 
        finish(); 
       } 
      } 
     }); 
//  Életcsik frissitése az életnek megfelelően 
     new Thread() { 
      @Override 
      public void run() { 
       while (true) { 
        if (lv.getRobot().getHealth() <= 0) { 
         runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           healthBar.setImageResource(R.drawable.battery5); 

          } 
         }); 

        } else if (lv.getRobot().getHealth() <= 25) { 
         runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           healthBar.setImageResource(R.drawable.battery4); 

          } 
         }); 
        } else if (lv.getRobot().getHealth() <= 50) { 
         runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           healthBar.setImageResource(R.drawable.battery3); 

          } 
         }); 
        } else if (lv.getRobot().getHealth() <= 75) { 
         runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           healthBar.setImageResource(R.drawable.battery2); 

          } 
         }); 
        }else if(lv.getRobot().getHealth() >= 75){ 
         runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           healthBar.setImageResource(R.drawable.battery); 

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

      } 
     }.start(); 
    } 

    @Override 
    protected void onPause() { 
     overridePendingTransition(0, 0); 
     super.onPause(); 
    } 



// TODO: 
    @Override 
    protected void onRestoreInstanceState(Bundle savedInstanceState) { 

     lv.getRobot().setX(savedInstanceState.getInt(playerX)); 
     lv.getRobot().setY(savedInstanceState.getInt(playerY)); 
     Log.d("LoL","Loaded y:"+savedInstanceState.getInt(playerY)); 
     lv.getRobot().setHealth(savedInstanceState.getInt(playerH)); 
     super.onRestoreInstanceState(savedInstanceState); 
    } 

    @Override 
    protected void onSaveInstanceState(Bundle outState) { 

     outState.putInt(playerX , lv.getRobot().getX()); 
     outState.putInt(playerY, lv.getRobot().getY()); 
     Log.d("LoL","Saved y:"+lv.getRobot().getY()); 
     outState.putInt(playerH, lv.getRobot().getHealth()); 
     super.onSaveInstanceState(outState); 
    } 



// iránygombok kezelése 
    private class mListener implements OnTouchListener { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: 

       switch (v.getId()) { 
       case R.id.left: 
        lv.getRobot().moveLeft(); 
        break; 
       case R.id.right: 
        lv.getRobot().moveRight(); 
        break; 
       case R.id.jump: 
        lv.getRobot().jump(); 
        break; 
       case R.id.fire: 
        lv.getRobot().shot(); 
        break; 
       } 
       break; 

      case MotionEvent.ACTION_UP: 
       switch (v.getId()) { 
       case R.id.left: 
        lv.getRobot().stopMovingLeft(); 
        break; 
       case R.id.right: 
        lv.getRobot().stopMovingRight(); 
        break; 
       case R.id.fire: 
        lv.getRobot()._shot(); 
        break; 
       } 
       break; 

      } 
      return true; 
     } 

    } 
} 

Class2의

package hu.cig.vob; 

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Iterator; 
import java.util.List; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Rect; 
import cug.hu.vob.R; 

public class Robot { 
    private Bitmap icon, currIcon, iconShot; 
    private int x, y, speedX = 0, speedY = 0, health = 100; 
    private final int MOVESPEED = 3, JumpSpeed = 15; 
    private boolean isMovingLeft = false, isMovingRight = false, 
      isFalling = true, isJumping = false, canJump = true; 
    private Rect bottom, horizontal; 
    private Context context; 
    private List<Bullet> bullets = Collections 
      .synchronizedList(new ArrayList<Bullet>()); 


    public Robot(int in_x, int in_y, Bitmap i, float sc, Context c) { 
     context = c; 

     icon = i; 
     currIcon = icon; 
     iconShot = BitmapFactory.decodeResource(c.getResources(), 
       R.drawable.shot_right); 

     x = in_x * (icon.getWidth()/2); 
     y = in_y * (icon.getHeight()/2); 
     y = (int) (sc - y); 

     // for colliding 
     horizontal = new Rect((int) (x + icon.getWidth() * (31.5/100)), 
       y + 5, (int) (x + icon.getWidth() - icon.getWidth() 
         * (31.5/100)), y + icon.getHeight() - 5); 

     bottom = new Rect((int) (x + icon.getWidth() * (31.5/100) + 5), y 
       + icon.getHeight() - 10, (int) (x + icon.getWidth() 
       - icon.getWidth() * (31.5/100) - 5), y + icon.getHeight()); 
    } 

    public void update(List<Block> blocks) { 
     int oldX = x, oldY = y; 
     if (!(x + speedX < 0 || x + speedX > LevelView.intScreenWidth)) { 
      x += speedX; 
     } 

     updateRect(); 

     for (int i = 0; i < blocks.size(); i++) { 
      if (horizontal.intersect(blocks.get(i).getRect())) { 
       stopMovingRight(); 
       stopMovingLeft(); 
       x = oldX; 
       updateRect(); 
      } 
     } 


     if (bullets.size() > 0) { 
      Iterator<Bullet> it = bullets.iterator(); 
      while (it.hasNext()) { 
       Bullet b = it.next(); 
       if (b.getCx() > LevelView.screenWidth) { 
        it.remove(); 
       } else { 
        b.update(); 
       } 

       Iterator<Block> itt = blocks.iterator(); 
       while (itt.hasNext()) { 
        Block bb = itt.next(); 
        if (bb.getRect().intersect(b.getRect())) { 
         it.remove(); 
        } 
       } 
      } 
     } 


     // @graviti" 

     if (isJumping) { 
      y -= speedY; 
      speedY--; 
      if (speedY == 0) { 
       isFalling = true; 
       isJumping = false; 
      } 
      updateRect(); 
     } 

     if (isFalling) { 
      y += JumpSpeed - 5; 
      canJump = false; 
      updateRect(); 
     } 

     for (Block b : blocks) { 
      if (bottom.intersect(b.getRect())) { 
       y = oldY; 
       updateRect(); 
       canJump = true; 
      } 
     } 
    } 

    private void updateRect() { 
     horizontal = new Rect((int) (x + icon.getWidth() * (31.5/100)), 
       y + 10, (int) (x + icon.getWidth() - icon.getWidth() 
         * (31.5/100)), y + icon.getHeight() - 10); 
     bottom = new Rect((int) (x + icon.getWidth() * (31.5/100) + 5), y 
       + icon.getHeight() - 10, (int) (x + icon.getWidth() 
       - icon.getWidth() * (31.5/100) - 5), y + icon.getHeight() - 2); 
    } 

    public void moveLeft() { 
     speedX = -MOVESPEED; 
     isMovingLeft = true; 
    } 

    public void moveRight() { 
     speedX = MOVESPEED; 
     isMovingRight = true; 
    } 

    public void stopMovingLeft() { 
     isMovingLeft = false; 
     stop(); 
    } 

    public void stopMovingRight() { 
     isMovingRight = false; 
     stop(); 
    } 

    public void stop() { 
     if (isMovingRight == false && isMovingLeft == false) { 
      speedX = 0; 
     } 

     if (isMovingRight == true && isMovingLeft == false) { 
      moveRight(); 
     } 

     if (isMovingRight == false && isMovingLeft == true) { 
      moveLeft(); 
     } 
    } 

    public Bitmap getIcon() { 
     return currIcon; 
    } 

    public int getX() { 
     return x; 
    } 

    public int getY() { 
     return y; 
    } 

    public int getSpeed() { 
     return speedX; 
    } 

    public boolean isMovingLeft() { 
     return isMovingLeft; 
    } 

    public boolean isMovingRight() { 
     return isMovingRight; 
    } 

    public Rect getBottomRect() { 
     return bottom; 
    } 

    public Rect getHRect() { 
     return horizontal; 
    } 

    public int getHealth() { 
     return health; 

    } 

    public void setX(int x) { 
     this.x = x; 
    } 

    public void setY(int y) { 
     this.y = y; 
    } 

    public void setHealth(int health) { 
     this.health = health; 
    } 

    public void shot() { 
     currIcon = iconShot; 
     Bullet b = new Bullet((float) (x + iconShot.getWidth()), 
       (float) (y + ((26.31 * iconShot.getHeight())/100)), 
       Helper.convertPx_Dpi(10, context), 2); 
     bullets.add(b); 
    } 

    public void _shot() { 
     currIcon = icon; 
    } 

    public List<Bullet> getBullets() { 
     return bullets; 
    } 

    public void jump() { 
     if (!isJumping && canJump) { 
      isJumping = true; 
      isFalling = false; 
      speedY = JumpSpeed; 
     } 
    } 



    public void increaseHealth(int x){ 
     health += x; 
     if(health > 100){ 
      health = 100; 
     } 
    } 

    public void degreeseHealth(int a) { 
     health -= a; 
    } 
} 
+0

다음은 Character 클래스입니다. [Class2 (Character)] – Chrys

+0

당신이 말하는 '나쁜 번호'가 무엇인지 모르겠지만 [Shared Preferences] (http://developer.android.com/reference/android/content/SharedPreferences.html) 원시 타입 값을 저장하고 게임이 다시 시작될 때로드합니다. –

+0

사진에서 값 450을 저장하고로드하는 것을 볼 수 있습니다 ... 화면 잠금을 해제하면 갑자기 숫자 1010을 절약 할 수 있습니다 ... 문제를 해결할 수 없다면 공유 환경 설정을 사용할 것입니다. 아직까지는) 그러나 나는이 방법 (만약에 효과가있다면)이 더 쉽다고 생각한다. :) – Chrys

답변

0

잠금 화면에 의해 가려하는 동안 앱 다시 시작할 수 있습니다. "이력서가 잠금 화면에 의해 숨겨져 있습니다"와 "이력서가 실제로 표시됨"의 차이점을 알려면 창 포커스를 확인할 수 있습니다.

자세한 내용은 Making Android Games that Play Nice을 참조하십시오.

"실제로 표시 될 때까지 대기"하는 다른 방법은 게임을 다시 시작하기 전에 이력서를받은 후 첫 번째 Activity.onUserInteraction을 기다리는 것입니다.

+0

나는 왜 이런 일이 일어나지 않았는가? 플레이어가 점프 버튼을 눌렀을 때만 y 좌표가 바뀐다. 이 방법들이 언제 caled되는지 언제 (그리고 몇 번이나) ... – Chrys

관련 문제