我在想...有没有办法可以在特定的时间内从数字中减去32?比如500密耳? 如果你能提供帮助,那就太好了!
谢谢!
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 :(得分:1)
嗯,这是我为你开发的可爱代码。我添加了关键字static
,以便能够在不创建任何对象的情况下从main
调用它,但它不会使用静态上下文中的任何内容。
正如我在代码中的注释试图解释的那样,这不是一个完美的解决方案,它只是一个开始,你可能会遇到诸如多线程错误之类的问题(如果你决定使用一个单独的线程来更新位置)如果方法的主体需要一段时间来执行,则会出现轻微的计时问题。
如果您认为纳秒精度对于您的目的来说有点太多,请记住还有Thread.sleep(int milis)
。
以下是代码(尝试更改调用moveLeft(int, int)
的值以查看结果):
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.
}
}
}