我的目标是在游戏无法到达后端时更改用户的屏幕。我的代码按预期执行,除非屏幕永远不会改变。这里的初始呼叫:HTTP请求后在单独的线程上更改呈现屏幕
timer.testTimeToServer(api, game);
这里的计时器对象的类。我把(我的网址)代替我的后端的实际IP地址:
public class CustomTimer {
private static final float timeToDrop = 2000;
private float time = 0;
private StopWatch watch = new StopWatch();
public void testTimeToServer(ApiCall api,final proofOfConcept game){
watch.start();
api.httpGetWithCallback("(my url)/api/v1/character", new CallBack(){
@Override
public void callback(String resp){
System.out.println("Server Responded");
time = watch.getTime();
watch.stop();
watch.reset();
if(time > timeToDrop){
game.setScreen(new GameOverScreen(game, false));
System.out.println("Should have switched screen")
}
}
});
}
}
这里是在API对象的httpGetWithCallback方法:
public void httpGetWithCallback (final String URL, final CallBack callback){
Thread th = new Thread(new Runnable(){
@Override
public void run() {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
httpRequest.setUrl(URL);
httpRequest.setHeader("Content-Type", "application/json");
httpRequest.setTimeOut(timeoutTimeInMilli);
Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String successValue = httpResponse.getResultAsString();
if (successValue.contains("\"total_count\": 0"))//wrong credentials
{
callback.callback("EMPTY");
} else//there was a match yo! should probably have a unique conststraint on username. too hard eff it
{
callback.callback(successValue);
}
}
@Override
public void failed(Throwable t) {
callback.callback("FAILED");
}
@Override
public void cancelled() {
callback.callback("CANCELLED");
}
});
}
}
);
}
});
th.start();
threads.add(th);
}
我很为难,因为代码打印出“应该切换屏幕“,所以它的行为像预期的那样,除了游戏被冻结并且屏幕切换从未实际发生。
OpenGL不能很好地处理多线程。 –
您是否尝试在更改屏幕的渲染方法内创建验证? 在java中,当你将变量传递给方法时,它们是实例的副本,所以在这个方法中调用game.setScreen 对原始实例不起作用,这不是像C,C++这样的指针。您需要以静态方式访问游戏对象,或者在渲染方法中验证它并更改屏幕。哦,你需要调用dispose();更换屏幕之后... – Hllink