2016-07-27 5 views
0

주 활동이 있고 해당 XML 레이아웃에는 게임 객체 (내 탱크 및 10 명의 적), 내 탱크 및 총알을 제어하는 ​​몇 개의 버튼 및 내 점수를 표시하는 TextView를 그리는 사용자 정의보기가 있습니다. 내 사용자 정의보기는 절반 화면 게임 보드 GameSurfaceView 자바 클래스입니다. 여기 내 코드의 일부는 다음과 같습니다GameSurfaceView에서 컨텍스트를 얻는 방법은 무엇입니까?

public class GameSurfaceView extends SurfaceView implements Runnable { 
    private static Context gContext; 
    public GameSurfaceView(Context context, AttributeSet attributeSet) { 
     super(context, attributeSet); 
     holder = getHolder(); 
     holder.addCallback(new SurfaceHolder.Callback() { 
     resume(); 
     gContext = context; 
    } 
    public void resume() { 
     isRunning = true; 
     gameThread = new Thread(this); 
     gameThread.start(); 
    } 
    public void pause() { 
     isRunning = false; 
     boolean retry = true; 
     while (retry) { 
      try { 
       gameThread.join(); 
       retry = false; 
      } catch (InterruptedException e) { 
       // try again shutting down the thread 
      } 
     } 
    } 
    @Override 
    public void run() { 
     while (isRunning) { 
      // We need to make sure that the surface is ready 
      if (!holder.getSurface().isValid()) { 
       continue; 
      } 
      long started = System.currentTimeMillis(); 

      // update 
      step(); 

      // draw 
      Canvas canvas = holder.lockCanvas(); 
      if (canvas != null) { 
       render(canvas); 
       holder.unlockCanvasAndPost(canvas); 
      } 

      //detect all possible collisions 
      detectCollisions(); 

      float deltaTime = (System.currentTimeMillis() - started); 
      int sleepTime = (int) (FRAME_PERIOD - deltaTime); 
      if (sleepTime > 0) { 
       try { 
        gameThread.sleep(sleepTime); 
       } catch (InterruptedException e) { 
       } 
      } 
      while (sleepTime < 0) { 
       step(); 
       sleepTime += FRAME_PERIOD; 
      } 
     } 
    } 

    //Called from MainActivity 
    public void dispatchKey(int tDirection) { 
     Toast.makeText(gContext, "Hi", Toast.LENGTH_LONG).show(); 
     gameStarted = true; 
     if (tDirection == FIRE) 
      Fire(); 
     else if (tDirection != tank.Direction) 
      turnTankDirection = tDirection; 
    } 
    private void detectCollisions() { 
     //Collision Detection between tank and enemy 
     Toast.makeText(gContext, "Collision", Toast.LENGTH_LONG).show(); 
    } 
} 

내 질문 : dispatchKey에서 토스트()를 실행 올바르게하지만 토스트 detectCollisions (에) 힘 가까이를 만드는 이유는 1? 2 detectCollisions() 메서드에서 TextView를 업데이트하는 방법은 무엇입니까? 3- detectCollisions() 메서드에서 충돌이 감지되었을 때 DialogAlert를 표시하는 방법은 무엇입니까? 내 문제는 주로 gContext 변수와 관련이 있습니다. 감사합니다. .

+0

오류 로그/스택 트레이스를 기입하십시오 추락. – ishmaelMakitla

+0

그러나 일부 하드웨어 제한으로 인해 실제 장치에서만 프로젝트를 테스트 할 수 있습니다. – Ahmad

답변

0

질문 1 : 아마도 두 번째 스레드에 영향을 미칠 수 있습니다. dispatchKey()가 Activity에서 호출되는 동안, detectCollision()은 틀린 스레드에서 호출됩니다. detectCollision()을 활동에서 호출하려고 했습니까?

질문 3 : 귀하의 활동이 청취를 구현하도록하십시오. 충돌이 감지되면 호출됩니다. 당신이 질문 한 용액과 2로 사용할 수 같은 일이


당신은 시도해야한다 : 이것은 무엇의 원인이 될 수 있습니다에 대한 단서가있을 수 있기 때문에

MainActivity.this.runOnUiThread(new Runnable() { 
    public void run() { 
     //Make toast or manipulate TextView 
    } 
}); 
+0

예, activity에서 detectCollision()을 호출하면 토스트가 표시됩니다. 그렇다면 어떻게 이러한 문제를 해결할 수 있습니까? 저는 GameSurfaceView 클래스에서 이러한 작업을하고 싶지 않기 때문입니다. – Ahmad

+0

runOnUiThread를 사용한 편집 참조 – user2605841

+0

실례합니다.이 코드를 어디에 넣어야합니까? 내 detectCollision() 메서드에서이 오류가 발생합니다 : "game.tank.MainActivity"둘러싸는 클래스가 아닙니다. – Ahmad

관련 문제