如何使用3D LWJGL创建多人游戏

时间:2015-03-25 22:06:21

标签: java lwjgl

我一直在努力创造一个MMO 3D游戏(我不确定游戏的名称或目标......还是在不确定中)。我尝试过使用java套接字,甚至尝试过KryoNet,但我仍然无法弄清楚如何将多人游戏集成到游戏中!

这是我的主类,我的预加载类和我的播放器类的代码。(顺便说一下,它们没有类声明,包声明或导入)

主类:

public static void main(String[] args) throws Exception {
    DisplayManager.createDisplay();
    PreLoading preLoading = new PreLoading();
    Loader loader = preLoading.loader;
    Camera camera = preLoading.camera;
    Player player = preLoading.player;
    MasterRenderer renderer = preLoading.renderer;
    Terrain terrain = preLoading.terrain;
    GuiRenderer guiRenderer = preLoading.guiRenderer;
    while (!PreLoading.finished) {
        if (PreLoading.finished) {
            break;
        }
    }
    DEBUG(1, "Starting Game!");
    while (!Display.isCloseRequested()) {
        player.move(terrain);
        camera.move();
        renderer.processEntity(player);
        renderer.processTerrain(terrain);
        for (Entity entity : preLoading.entities) {
            renderer.processEntity(entity);
        }
        renderer.render(preLoading.lights, camera);
        DisplayManager.updateFPS();
        DisplayManager.updateDisplay();

    }
    DEBUG(1, "Stoping Game!");
    guiRenderer.cleanUp();
    renderer.cleanUp();
    loader.cleanUP();
    DisplayManager.closeDisplay();
    DEBUG(1, "Game stopped!");
}

public static void DEBUG(int level, String msg) {
    Date d = new Date(System.currentTimeMillis());
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    String formatted = sdf.format(d);
    switch (level) {
    case (1):
        System.out.println("[" + formatted + "] [Information] " + msg);
        break;
    case (2):
        System.out.println("[" + formatted + "] [Warning] " + msg);
        break;
    case (3):
        System.out.println("[" + formatted + "] [Error] " + msg);
        break;
    }
}

PreLoading Class:

public static Loader loader = new Loader();
public static TerrainTexture backgroundTexture = new TerrainTexture(loader.loadTexture("grassy"));
public static TerrainTexture rTexture = new TerrainTexture(loader.loadTexture("mud"));
public static TerrainTexture gTexture = new TerrainTexture(loader.loadTexture("pinkflowers"));
public static TerrainTexture bTexture = new TerrainTexture(loader.loadTexture("mossPath256"));

public static TerrainTexturePack texturePack = new TerrainTexturePack(backgroundTexture, rTexture, gTexture, bTexture);
public static TerrainTexture blendMap = new TerrainTexture(loader.loadTexture("blendMap"));
public static TexturedModel pine = new TexturedModel(ObJLoader.loadObjModel("pine", loader), new ModelTexture(loader.loadTexture("pine")));
public static TexturedModel tree = new TexturedModel(ObJLoader.loadObjModel("lowPolyTree", loader), new ModelTexture(loader.loadTexture("lowPolyTree")));
public static TexturedModel grass = new TexturedModel(ObJLoader.loadObjModel("grassModel", loader), new ModelTexture(loader.loadTexture("grassTexture")));

public static ModelTexture fernTextureAtlas = new ModelTexture(loader.loadTexture("fern"));

public static TexturedModel fern = new TexturedModel(ObJLoader.loadObjModel("fern", loader), fernTextureAtlas);

public static TexturedModel lamp = new TexturedModel(ObJLoader.loadObjModel("lamp", loader), new ModelTexture(loader.loadTexture("lamp")));

public static Terrain terrain = new Terrain(0, -1, loader, texturePack, blendMap, "heightMap");

public static List<Entity> entities = new ArrayList<Entity>();

public static MasterRenderer renderer = new MasterRenderer(loader);

public static TexturedModel playerModel = new TexturedModel(ObJLoader.loadObjModel("person", loader), new ModelTexture(loader.loadTexture("playerTexture")));
public Player player = new Player(playerModel, new Vector3f(100, 5, -150), 0, 180, 0, 0.6f);
public static boolean finished = false; 
public Camera camera = new Camera(player);
//List<GuiTexture> guis = new ArrayList<GuiTexture>();
public static GuiRenderer guiRenderer = new GuiRenderer(loader);
public static List<Light> lights = new ArrayList<Light>();
public PreLoading() throws Exception {
    fernTextureAtlas.setNumberOfRows(2);
    Random random = new Random(676452);
    for (int i = 0; i < 100; i++) {
        if (i % 2 == 0) {
            float x = random.nextFloat() * 800 - 400;
            float z = random.nextFloat() * -600;
            float y = terrain.getHeightOfTerrain(x, z);

            entities.add(new Entity(fern, random.nextInt(4), new Vector3f(x, y, z), 0, random.nextFloat(), 0, 0.9f));

        }
        if (i % 5 == 0) {
            float x = random.nextFloat() * 800 - 400;
            float z = random.nextFloat() * -600;
            float y = terrain.getHeightOfTerrain(x, z);

            entities.add(new Entity(pine, new Vector3f(x, y, z), 0, random.nextFloat(), 0, 3));
            x = random.nextFloat() * 800 - 400;
            z = random.nextFloat() * -600;
            y = terrain.getHeightOfTerrain(x, z);

            entities.add(new Entity(tree, new Vector3f(x, y, z), 0, random.nextFloat() * 360, 0, random.nextFloat() * 0.1f + 0.6f));
        }
        float x = random.nextFloat() * 800 - 400;
        float z = random.nextFloat() * -600;
        float y = terrain.getHeightOfTerrain(x, z);

        entities.add(new Entity(grass, new Vector3f(x, y, x), 0, random.nextFloat() * 360, 0, 1));
        grass.getTexture().setHasTransparency(true);
        grass.getTexture().setUseFakeLighting(true);
        grass.getTexture().setHasTransparency(true);
    }



    lights.add(new Light(new Vector3f(0, 10000, -7000), new Vector3f(0.4f, 0.4f, 0.4f)));
    lights.add(new Light(new Vector3f(185, 10, -293), new Vector3f(2, 0, 0), new Vector3f(1, 0.01f, 0.002f)));
    lights.add(new Light(new Vector3f(370, 17, -300), new Vector3f(0, 2, 2), new Vector3f(1, 0.01f, 0.002f)));
    lights.add(new Light(new Vector3f(293, 7, -305), new Vector3f(2, 2, 0), new Vector3f(1, 0.01f, 0.002f)));

    entities.add(new Entity(lamp, new Vector3f(185, terrain.getHeightOfTerrain(185, -293), -293), 0, 0, 0, 1));
    entities.add(new Entity(lamp, new Vector3f(370, terrain.getHeightOfTerrain(370, -300), -300), 0, 0, 0, 1));
    entities.add(new Entity(lamp, new Vector3f(293, terrain.getHeightOfTerrain(293, -305), -305), 0, 0, 0, 1));

    MasterRenderer renderer = new MasterRenderer(loader);

    TexturedModel playerModel = new TexturedModel(ObJLoader.loadObjModel("person", loader), new ModelTexture(loader.loadTexture("playerTexture")));
    Player player = new Player(playerModel, new Vector3f(100, 5, -150), 0, 180, 0, 0.6f);

    Camera camera = new Camera(player);
    //List<GuiTexture> guis = new ArrayList<GuiTexture>();
    GuiRenderer guiRenderer = new GuiRenderer(loader);
    finished = true;
}

玩家等级:

private String customName;
private boolean customNameVisible;
private String displayName;
private String username;
private String address;
private boolean allowFlight;
private int energy;
private int health;
private int hunger;
private int thirst;
private boolean isFalling = false;
private boolean isFlying;
private float experience;
private int maxHealth;
private String playerListName;
private float walkSpeed;
private float runSpeed;
private float turnSpeed;
private float jumpPower;
private float straifSpeed;
private float gravityPower;
private int gameMode;
private String UUID;
private String password;
private String IPAddress;

private float currentSpeed = 0;
private float currentStraifSpeed = 0;
private float currentTurnSpeed = 0;
private float upwardsSpeed = 0;
public float angleChange;
public boolean thirdPerson = false;
private float X;
private float Y;
private float Z;
public Player(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, float scale)  throws Exception {
    super(model, position, rotX, rotY, rotZ, scale);
    this.walkSpeed = Constants.Player_Walk_Speed;
    this.runSpeed = Constants.Player_Run_Speed;
    this.turnSpeed = Constants.Player_Turn_Speed;
    this.jumpPower = Constants.Player_Jump_Power;
    this.straifSpeed = Constants.Player_Straif_Speed;
    this.gravityPower = Constants.Player_Gravity_Power;
    this.health = (int) Constants.Player_Default_Health;
    this.maxHealth = (int) Constants.Player_Default_Health;
    this.hunger = (int) Constants.Player_Default_Hunger;
    this.energy = (int) Constants.Player_Default_Energy;
    this.X = position.x;
    this.Y = position.y;
    this.Z = position.z;
}

public void move(Terrain terrain) throws Exception {
    checkInputs();
    this.increaseRotation(0, currentTurnSpeed * DisplayManager.getFrameTimeSeconds(), 0);
    currentTurnSpeed = 0;
    float distance = currentSpeed * DisplayManager.getFrameTimeSeconds();
    float dx = (float) (distance * Math.sin(Math.toRadians(this.getRotY())));
    float dz = (float) (distance * Math.cos(Math.toRadians(this.getRotY())));
    float distance1 = currentStraifSpeed * DisplayManager.getFrameTimeSeconds();
    float dx1 = (float) (distance1 * Math.sin(Math.toRadians(this.getRotY() + 90)));
    float dz1 = (float) (distance1 * Math.cos(Math.toRadians(this.getRotY() + 90)));
    this.increasePosition(dx, 0, dz);
    this.increasePosition(dx1, 0, dz1);
    upwardsSpeed += gravityPower * DisplayManager.getFrameTimeSeconds();
    this.increasePosition(0, upwardsSpeed * DisplayManager.getFrameTimeSeconds(), 0);
    float terrainHeight = terrain.getHeightOfTerrain(this.getPosition().x, this.getPosition().z);
    if (this.getPosition().y < terrainHeight) {
        upwardsSpeed = 0;
        isFalling = false;
        this.getPosition().y = terrainHeight;
    }
    if (!thirdPerson) {
        angleChange = Mouse.getDX() * 0.3f;
        this.increaseRotation(0, -angleChange, 0);
    }
    this.X = this.getPosition().x;
    this.Y = this.getPosition().y;
    this.Z = this.getPosition().z;
}

public void gainHealthAndEnergy(){
    long befTime = System.currentTimeMillis();
    while(true){
        if (System.currentTimeMillis() > befTime + 600){
            if(!(energy <= 0)){
                energy += energy / 2;
            } else {
                energy += 20;
            }
            break;
        }
        while(true){
            if (System.currentTimeMillis() > befTime + 2000){
                if (hunger > 950)
                    health += 5;
                if (hunger < 50)
                    health -= 5;
                break;
            }
        }
    }
}

public String getCustomName() {
    return customName;
}

public void setCustomName(String customName) {
    this.customName = customName;
}

public boolean isCustomNameVisible() {
    return customNameVisible;
}

public void setCustomNameVisible(boolean customNameVisible) {
    this.customNameVisible = customNameVisible;
}

public String getDisplayName() {
    return displayName;
}

public void setDisplayName(String displayName) {
    this.displayName = displayName;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public boolean isAllowFlight() {
    return allowFlight;
}

public void setAllowFlight(boolean allowFlight) {
    this.allowFlight = allowFlight;
}

public int getEnergy() {
    return energy;
}

public void setEnergy(int energy) {
    this.energy = energy;
}

public int getHealth() {
    return health;
}

public void setHealth(int health) {
    this.health = health;
}

public int getHunger() {
    return hunger;
}

public void setHunger(int hunger) {
    this.hunger = hunger;
}

public int getThirst() {
    return thirst;
}

public void setThirst(int thirst) {
    this.thirst = thirst;
}

public boolean isFalling() {
    return isFalling;
}

public void setFalling(boolean isFalling) {
    this.isFalling = isFalling;
}

public boolean isFlying() {
    return isFlying;
}

public void setFlying(boolean isFlying) {
    this.isFlying = isFlying;
}

public float getExperience() {
    return experience;
}

public void setExperience(float experience) {
    this.experience = experience;
}

public int getMaxHealth() {
    return maxHealth;
}

public void setMaxHealth(int maxHealth) {
    this.maxHealth = maxHealth;
}

public String getPlayerListName() {
    return playerListName;
}

public void setPlayerListName(String playerListName) {
    this.playerListName = playerListName;
}

public float getWalkSpeed() {
    return walkSpeed;
}

public void setWalkSpeed(float walkSpeed) {
    this.walkSpeed = walkSpeed;
}

public int getGameMode() {
    return gameMode;
}

public void setGameMode(int gameMode) {
    this.gameMode = gameMode;
}

public String getActualName() {
    return username;
}

public String getUUID() {
    return UUID;
}

public String getPassword() {
    return password;
}

public String getIPAddress() {
    return IPAddress;
}

public float getX() {
    return Z;
}
public float getY() {
    return Y;
}
public float getZ() {
    return Z;
}

public void jump() {
    if (!isFalling) {
        this.upwardsSpeed = jumpPower;
        isFalling = true;
    } else if (isFalling && allowFlight){
        this.upwardsSpeed = jumpPower * 3f;
        this.walkSpeed = Constants.Player_Run_Speed * 3f;
    }
}

public void checkInputs() throws IOException {
    if (Keyboard.isKeyDown(Keyboard.KEY_W) && !Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
        this.currentSpeed = walkSpeed;
    } else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
        this.currentSpeed = -walkSpeed * 0.96f;
    } else if (Keyboard.isKeyDown(Keyboard.KEY_W) && Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
        this.currentSpeed = runSpeed;
    } else {
        this.currentSpeed = 0;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        if (!thirdPerson) {
            this.currentStraifSpeed = -straifSpeed;
            //MainGameLoop.outToServer.writeBytes("Straifing: RIGHT");
        } else {
            currentTurnSpeed = -turnSpeed;
            //MainGameLoop.outToServer.writeBytes("Tuning: RIGHT");
        }
    } else if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        if (!thirdPerson) {
            this.currentStraifSpeed = straifSpeed;
            //MainGameLoop.outToServer.writeBytes("Straifing: LEFT");
        } else {
            currentTurnSpeed = turnSpeed;
            //MainGameLoop.outToServer.writeBytes("Tuning: LEFT");
        }
    } else if (Keyboard.isKeyDown(Keyboard.KEY_RCONTROL)) {
        MainGameLoop.DEBUG(1,"Debug message here!");
    } else {
        this.currentStraifSpeed = 0;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
        jump();
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
        gravityPower += 0.5;
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
        gravityPower -= 0.5;
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD0)) {
        gravityPower = 0;
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_F)) {
        if (!allowFlight){
            this.allowFlight = true;
        } else {
            this.walkSpeed = Constants.Player_Walk_Speed;
            this.allowFlight = false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你可以看一下monkeyzone这是一个非常好的带有lwjgl的3D多人游戏的演示。我帮助我从那里获取代码并在我的多人游戏场景中使用。我推荐jmonkeyengine。如果您还没有尝试过,请给它一个机会。