음, 여기 제가 당신을 위해 개발 한 멋진 코드입니다. 객체를 만들지 않고 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.
}
}
}
에 Thread.sleep (500L) : 여기
코드 (결과를 확인moveLeft(int, int)
를 호출 값을 변경하려고)인가? 정확히 달성하려는 것은 무엇입니까? –나는 변수 (dx)가 있고 타일 기반 게임을하고있어 왼쪽으로 움직일 때 일정한 양의 32 dx를 빼야합니다. – LoafOfCat
질문이 너무 애매합니다. 올바른 해결책은 사용하는 UI 프레임 워크 (스윙, 기타)에 따라 다릅니다. 코드를 보여주세요. –