[英]Equivalent of JavaScript's splice in Java
我正在尝试将一些Javascript代码移植到Java中,并且到达了一个部分,在这里我似乎无法在没有各种错误的情况下移植代码。 没有实际的异常抛出,只是它不应该正常工作。 基本上,此代码是网络代码段的一部分,该代码段尝试在服务器收到新数据包时与服务器协调,因为即使没有数据包要应用,它也会使用客户端预测来保持播放器的移动。
我理解这个概念,但是似乎无法将其放入代码中。 代码部分使用数组上的splice
函数删除元素,因此我认为移植起来很容易。 我将在下面发布JS的代码段以及Java中的代码段,这些代码段会给我带来问题,并告诉我我做错了什么。 我很确定我也移植了错误的循环。
JavaScript:
var j = 0;
while (j < this.pending_inputs.length) {
var input = this.pending_inputs[j];
if (input.input_sequence_number <= state.last_processed_input) {
// Already processed. Its effect is already taken into account
// into the world update we just got, so we can drop it.
this.pending_inputs.splice(j, 1);
} else {
// Not processed by the server yet. Re-apply it.
this.entity.applyInput(input);
j++;
}
}
Java:
for (int i = 0; i < pendingInputs.size(); i++) {
if (i <= lastProcCmd) {
// Already proceesed command, remove it from pendingInputs
for (int j = 1; j < pendingInputs.size(); j++) {
pendingInputs.remove(j);
}
} else {
applyCmd(pendingInputs.get(i));
}
}
编辑所以我将代码更改为此:
// Server reconciliation
int j =0;
while (j < pendingInputs.size()) {
String cmd = pendingInputs.get(j);
if (pendingInputs.indexOf(cmd) <= lastProcCmd) {
pendingInputs.remove(j);
} else {
applyCmd(cmd);
j++;
}
}
而且我仍然有一个问题,所以我认为它在代码的其他地方。 这是多人游戏代码中使用客户端预测和服务器和解,是否可以帮助使用这些文章: 文章
待处理的输入是String
的ArrayList
,它们表示命令,例如“ Left”或“ Right”。 另一个问题是,即使我使用同步块来防止任何ConcurrentModificationException
发生在重要的地方,我的网络侦听器也在另一个线程上。 他的代码很难移植,因为我不熟悉JS到Java。
未经测试,但看起来很近:
for (Iterator<String> iter = pendingInputs.iterator(); iter.hasNext(); ) {
String cmd = iter.next();
if(pendingInputs.indexOf(cmd) <= lastProcCmd){
iter.remove();
}else{
applyCmd(cmd);
}
}
注意事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.