[英]Java - Application crashed on Thread.sleep method
I have a function for my monsters to walk. 我有让怪物走的功能。 It will be able to choose the direction and distance randomly and move the monster when called.
它将能够随机选择方向和距离,并在被召唤时移动怪物。 Right now I have the method being called every frame in the render method:
现在,我在render方法的每一帧都调用了该方法:
for(Monster monster : monsters) {
renderer.processEntity(monster);
monster.monsterWalk();
}
This is good so far, but it makes the monster shake around because it is rapidly choosing values, I want it to move somewhere, wait 5 seconds, and then make another decision on where to move. 到目前为止,这是一件好事,但是它会使怪物摇晃,因为它正在迅速选择值,我希望它移动到某个地方,等待5秒钟,然后再决定要移动到哪里。
My problem is when I add the Thread.sleep(x) method, and the screen goes black and the program becomes unresponsive. 我的问题是当我添加Thread.sleep(x)方法时,屏幕变黑,程序无响应。
Here is the walk method: 这是步行方法:
public void monsterWalk() {
//Make direction decision
Random random = new Random();
switch(random.nextInt(4)) {
case 0:
setPosition(new Vector3f(position.x, position.y, position.z += mobSpeed)); //forward
break;
case 1:
setPosition(new Vector3f(position.x, position.y, position.z -= mobSpeed)); //backward
break;
case 2:
setPosition(new Vector3f(position.x += mobSpeed, position.y, position.z)); //right
break;
case 3:
setPosition(new Vector3f(position.x -= mobSpeed, position.y, position.z)); //left
}
try {
Thread.sleep(random.nextInt(5000) + 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I haven't used LWJGL myself, but in almost every UI framework I've seen, there's one thread which is reserved for UI operations: 我自己没有使用过LWJGL,但是在我见过的几乎每个UI框架中,都有一个线程保留给UI操作:
In your code, you're calling Thread.sleep
which blocks the thread for that period of time - if you do that on a UI thread (and if LWJGL works in the same way as those other frameworks) then you're preventing the UI from refreshing while it's blocking. 在您的代码中,您正在调用
Thread.sleep
,该线程将在该时间段内阻塞线程-如果您在UI线程上执行此操作(并且LWJGL与其他框架的工作方式相同),则您将阻止UI阻止时刷新。
To perform actions periodically, you should use a timer of some sort. 要定期执行操作,应使用某种计时器。 The tricky part is that you'd want the timer to fire in the UI thread .
棘手的部分是您希望计时器在UI线程中触发。 Most frameworks provide some sort of dedicated support for this (eg Swing
Timer
) but I don't know if LWJGL does. 大多数框架为此提供某种形式的专用支持(例如Swing
Timer
),但是我不知道LWJGL是否支持。 Hopefully that's enough information to get you started looking for the best approach within LWJGL. 希望有足够的信息可以帮助您开始在LWJGL中寻找最佳方法。
I note the LWJGL timing documentation talks about this sort of thing a bit, but it's not quite the same. 我注意到LWJGL时机文档关于这种事情有点会谈,但它是不完全一样。 (It also refers to
Display.sync
, which I then can't find in the Javadoc, so it may be referring to an older version.) (它也指向
Display.sync
,然后我在Javadoc中找不到它,因此它可能是指向较旧的版本。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.