简体   繁体   中英

How to handle game object updates with kryonet client

I working on a simple multiplayer game in java2d that handles 4 players at a time. Here is a code sample that receives data from the server.

server.addListener(new Listener() {
   public void received (Connection connection, Object object) {

   }
});

My question is: when data it received such as the location of another player, how should I update it? Do I statically reference the game class an access it's player data, or do I pass the player object to the client class at the start? Is there a good way of doing this?

Thanks!

Well if you have a balloon for example that needs to show up on every ones screen then maybe you should have a static list that holds these objects and send that whole list or loop through it all and send each separately to the client and then on the client side it can have a static list to that it renders from every game loop.

Or you can pass the current game object that you need to update. For example you can extract the listener to external class instead of nesting it in the serever.addListener method. LIke this

package BTDOnlineToolKit;

import com.esotericsoftware.kryonet.*;

import packets.GeneralPackets.Ping;

public class NetworkHandler extends Listener {

    private Client clientObject;

    public NetworkHandler(Client clientObject) {
        this.clientObject = clientObject;
    }

    @Override
    public void connected(Connection connection) {
        clientObject.updateReturnTripTime();
        connection.updateReturnTripTime();
    }

    @Override
    public void disconnected(Connection connection) {
        super.disconnected(connection);
    }

    @Override
    public void idle(Connection connection) {
        super.idle(connection);
    }

    @Override
    public void received(Connection con, Object packet) {
        if (packet instanceof Ping) {
            Ping ping = (Ping) packet;
            if (ping.returned) {

            }
        }
    }

}

NetworkHandler netHandle = new NetworkHandler(Anyobjects you need it to parse);
Server.addListener(netHandle);

Dont forget you can also update the objects you need to update manully by making a method for that in the network handler.

And construct it before you start the server with all the things you need the connection to update for example you can pass a label object that shows ping or a enemy player object which you need to update atrributes of. But like i said You can have a static list to store those values but this is more scalable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM