我用java制作了一个简单的球和桨多人游戏。它用于MultiCastSocket
发送和接收数据。球仅在玩家
1 的系统上移动。球的位置由网络上的所有玩家发送。所有玩家都会收到数据,但只有 p1 以外的玩家会读取数据并更新他们的球位。现在这里的问题是,虽然球在 p1 上平稳移动,但在其他玩家的系统上却不是连续运动。屏幕上的球的离散实例是可见的。以下是我的代码的网络部分的代码片段:(这里 myTag 是球员号码,rec 是接收数据类的对象,它只接收数据并存储在名为的字符串中data
)
private class ScheduleTask extends TimerTask {
@Override
public void run() {
paddleArr[myTag].moveX();
for(int i=0; i<4; i++){
if(i != myTag){
if(!others.contains(i)){
Computer comPaddle = new Computer(paddleArr[i], ball);
if(paddleArr[i].isHorizontal()){comPaddle.moveSideways();}
else {comPaddle.move();}
}
}
}
if(myTag==0){ball.move();}
if(ball.getXdir()*ball.getXdir()+ball.getYdir()*ball.getYdir() >= 80){
ball.setXdir(ball.getXdir()*0.67);
ball.setYdir(ball.getYdir()*0.67);
}
if(newgame){
try {
socket = new MulticastSocket(4446);
group =InetAddress.getByName("228.6.7.8");
socket.joinGroup(group);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("error");
}
rec = new ReceiveData(socket, group, port, myTag);
newgame = false;
}
//System.out.println(rec.data);
if(bak > 10){
setAllPos(rec.data.trim());
}
bak++;
checkCollision();
repaint();
try {
socket = new MulticastSocket(4446);
group = InetAddress.getByName("228.6.7.8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = myTag+" "+(ball.getMyX())+" "+(ball.getMyY())+" "+(ball.getXdir())+" "+(ball.getYdir())+" "+(paddleArr[myTag].getMyX())+" "+(paddleArr[myTag].getMyY());
buf = str.getBytes();
// Create a DatagramPacket
DatagramPacket packet = new DatagramPacket(buf, buf.length,group, 4446);
// Do a send.
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("send failed");
}
// And when we have finished sending data close the socket
socket.close();
}
}
public void setAllPos(String s){
//System.out.println(s);
String[] data = s.split(" ");
if(myTag != 0){
if(data[0].equals("0"))
{
ball.setMyX(Double.parseDouble(data[1]));
ball.setMyY(Double.parseDouble(data[2]));
ball.setXdir(Double.parseDouble(data[3]));
ball.setYdir(Double.parseDouble(data[4]));
repaint();
//ball.move();
//paddleBottom.setMyX(Integer.parseInt(data[5]));
//content.udpPosition = data[5];
//System.out.println("Ball pos set");
}
}