gpt4 book ai didi

Java - 在特定时间内从一个数字中减去32

转载 作者:行者123 更新时间:2023-12-01 13:09:08 25 4
gpt4 key购买 nike

我想知道...有没有办法可以在特定时间内从一个数字中减去 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
}

最佳答案

嗯,这是我为您开发的一段可爱的代码。我添加了关键字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.
}
}
}

关于Java - 在特定时间内从一个数字中减去32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23031905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com