I have made a simple ball and paddle Multiplayer game in java. It uses MultiCastSocket
to send and receive data.Ball is being moved only on system of player
1. Position of ball is sent by all players on the network. All players receive the data and but only players other than p1 read it and update their ball position. Now the problem here is that although the ball is moving smoothly on p1 but on other player's systems it is not in continuous motion. Discrete instances of ball on the screen are visible.Following is a code snippet of the networking part of my code:
(here myTag is the player number
rec is an object of Receive data class that just receives data and stores in a String named 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");
}
}