2014-04-12 1 views
0

궁금합니다. 특정 시간 내에 숫자에서 32를 뺄 수있는 방법이 있습니까? 500 밀리 같은거야? 도움이된다면 좋을 것입니다.Java - 특정 시간 내에 숫자에서 32를 뺍니다.

감사합니다.

public void update() { 
x += dx; 

if(this.y % 32 == 0) { 
    this.tileY = this.y/32; 
} 

if(this.x % 32 == 0) { 
    this.tileX = this.x/32; 
} 

System.out.println(tileX); 

    } 

public void moveLeft() { 
// subtract 32 dx in 500 ms 
} 
+0

에 Thread.sleep (500L) : 여기

코드 (결과를 확인 moveLeft(int, int)를 호출 값을 변경하려고)인가? 정확히 달성하려는 것은 무엇입니까? –

+0

나는 변수 (dx)가 있고 타일 기반 게임을하고있어 왼쪽으로 움직일 때 일정한 양의 32 dx를 빼야합니다. – LoafOfCat

+0

질문이 너무 애매합니다. 올바른 해결책은 사용하는 UI 프레임 워크 (스윙, 기타)에 따라 다릅니다. 코드를 보여주세요. –

답변

1

음, 여기 제가 당신을 위해 개발 한 멋진 코드입니다. 객체를 만들지 않고 main에서 호출 할 수 있도록 키워드 static을 추가했지만 정적 컨텍스트에서는 아무 것도 사용하지 않습니다.

내 의견을 코드를 통해 설명하려고하면 완벽한 솔루션이 아니며 단지 시작일뿐입니다. 다중 스레드 오류와 같은 문제에 직면 할 수 있습니다 (별도의 스레드를 사용하여 위치를 업데이트하기로 결정한 경우).) 메서드의 본문이 실행하는 데 시간이 걸리는 경우 약간의 타이밍 문제가 발생할 수 있습니다.

나노초 정밀도가 너무 많아서 Thread.sleep(int milis)이라는 것을 기억하십시오.

public class Slider { 

    public static void main(String[] args) { 
    Thread thread = new Thread() { 
     @Override 
     public void run() { 
      /* 
      * If you are going to use something like this, beware you are multi-threading 
      * Make sure what you do is thread-safe 
      */ 
      moveLeft(32, 500); 
     } 
    }; 
    thread.start(); 
    } 

    public static void moveLeft(int distance, int milis) { 
    //time_px is how many nanoseconds the Thread can sleep until it has to move 1 dx 
    double time_px = (100000*milis)/distance; 
    if (time_px >= 1) { 
     //Get the milis and nanos, rounding for Thread.sleep 
     long time_round = (long) Math.floor(time_px); 
     long milis_sleep = time_round/100000; 
     System.out.print("Waiting " + milis_sleep + "ms "); 
     int nano_sleep = (int) (time_round%100000); 
     System.out.println(nano_sleep + "ns per dx"); 
     for (int i=0; i<distance; i++) { 
      try { 
       Thread.sleep(milis_sleep, nano_sleep); 
       /* 
       * Your code here 
       * A long code here might not get you the desired result since the sleeping does 
       * not account for the time spent processing the code. But this is a good start 
       */ 
       System.out.println("moving 1 dx"); 
      } 
      catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    else { 
     System.out.println("Cannot go that fast"); 
     //If you are moving that fast (more than 1 dx per nanosecond) then you need to change this up a little. 
    } 
    } 
} 
+0

이것은 완벽합니다! 감사! – LoafOfCat

관련 문제