spawning models help

6 replies [Last post]
Offline
Joined: 05/24/2011

Say I have a terrain set, and I want a model to spawn in a certain area, for just at the beginning of the game, I cant do it someone please help?
 
Please tell me how to do it using the BlueJ ide please.

KMacKenzie's picture
Offline
Joined: 12/10/2010
First off, if you haven't

First off, if you haven't already, read over lessons 1-3 here.
Once you have done those and understand how to build a simple game with Env3d, then it becomes fairly simple.
Create objects with the models and locations that you want, and at the start of the play method (before the while loop) add them into your environment.
Then, use a time counter (time variable with a ++; modifier in the game loop) and an if check to check if the time has reached the point you want to remove the objects.
Then, simply remove the objects from your environment.
Put something like this in your game's while loop...
if (time >= 3600) {
env.removeObject(YOUR OBJECT);
}
time++;
If you have done lessons 1-3 and dont undestand what I am saying here post the code you have so far and I will help you get it working.

Offline
Joined: 05/24/2011
Thanks so much

 I will try this right now, but I have one small question, before (its kinda irrelevant) but my small question is: is it possible to make a Multiplayer game with Env3d (like LAN and Internet) ?.
 
Thanks again for your help !

KMacKenzie's picture
Offline
Joined: 12/10/2010
 Yes its possible! Infact I

 Yes its possible!
Infact I made one a few months ago just to test it out. 
 
http://env3d.org/beta/node/157
(just have two people run the applet at the same time, or open it in two different browsers)
 
In order to make a multiplayer game however you will need a dedicated server, there are several methods that will produce various results depending on the quality of the server, software it runs, and how you communicate with it. The method used in the example I linked above is one of the most simple forms. (which is why it is a bit jittery) It communicates by sending information to a PHP script that writes to a simple .txt file. 
This method doesn't work well for real-time applications (like an FPS style shooter). But would probably work fine for an RPG, especially turn based.

Offline
Joined: 05/24/2011
Thanks

Thanks, but HOW would I make it, like could you give me the source of that world of zulu ? 

Offline
Joined: 01/06/2011
Multiplayer is definitely

Multiplayer is definitely possible, as Kenny showed. What he does is he sets up a web server, just like which would sit behind a website, and sends/request data from it. It's definitely possible, but it's probably best to start small and build up from there. I released a game called Gyroball for Xbox Live Indie Games back in March and it had multiplayer. I'm sure I could build something similar in Env3d. Real-time multiplayer is more complex and it takes a good deal of time to get good at. You don't even need a server or to know how to set up a server in order to do it if you do peer-to-peer networking (packets, containing data, are sent from one user running the game to other users).
 
Jason's tutorials do a good job of that. If you dedicate yourself to them for awhile it will eventually come. The best way to learn is just to follow along, type the code from the tutorials out yourself, and be persistent when something isn't working right.
 
You'll eventually be able to build something that has multiplayer, but it will take some patience and persistence. If you want to go for it though, definitely feel free to ask for more feedback here. Also, telling us what you tried to do or what code isn't working allows us to get a better idea of what you're doing and what kind of response to give.
 
Best of luck!

KMacKenzie's picture
Offline
Joined: 12/10/2010
I am afraid that the question

I am afraid that the question you are asking is far too complex to be answered in a forum post, you are going to need to learn some basic server side programming to set up proper communication or at the very least understand how to receive and store variables with php on a server. 
 
However, here is the source code of the two classes responsible for the networking from my example game. If you have more specific questions I will be happy to answer them.
 
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
 
/**
* A class to interact with the simple storage interface.
*/
public class SimpleBucket
{
    private String address;
    private URL url;
    
    /**
    * Create the bucket, must provide the bucket's URL
    */
    public SimpleBucket(String bucketURL) {
        this.address = bucketURL;
    }
    
    /**
    * Read the object id from the bucket
    */
    public String read(String objectId) throws Exception
    {
        URL url = new URL(address+"/"+objectId);
        BufferedReader stream = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer sb = new StringBuffer();
        char[] inputBuffer = new char[1000];
 
        while (true) {
            int c = stream.read(inputBuffer, 0, inputBuffer.length);
            if (c == -1) {
                break;
            }          
            sb.append(inputBuffer,0,c);
        }
        stream.close();
        return sb.toString();
    }
    
        /**
    * Read the object id from the bucket
    */
    public String[] readAll() throws Exception
    {
        URL url = new URL(address+"?includedata=true");
        BufferedReader stream = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer sb = new StringBuffer();
        char[] inputBuffer = new char[1000];
 
        while (true) {
            int c = stream.read(inputBuffer, 0, inputBuffer.length);
            if (c == -1) {
                break;
            }          
            sb.append(inputBuffer,0,c);
        }
        stream.close();
        return sb.toString().split("\n");
    }
  
    /**
    * Write some data to an object
    */
    public void write(String objectId, String data) throws Exception
    {
        URL url = new URL(address+"/"+objectId);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write("data="+URLEncoder.encode(data,"UTF-8"));
        wr.flush();          
        // ignore the output and return
        conn.getInputStream().close();      
        wr.close();
    }
    
    /**
    * Delete an object from a bucket
    */
    public void deleteObject(String objectId) throws Exception
    {
        read(objectId.trim()+"?delete=true");
    }
    
    /**
    * List all objects in a bucket that starts with some prefix.
    */
    public String [] listObjects(String prefix) throws Exception
    {
        if (prefix == null) {
            prefix = "";
        } else {
            prefix += "*";
        }
        return read(prefix).split("\n");
    }
}
 
 
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
import java.util.ArrayList;
import java.util.HashMap;
 
import env3d.Env;
import env3d.EnvApplet;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import javax.swing.JOptionPane;
 
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
 
import java.io.*;
import java.net.*;
 
/**
 * 
 * The Game class.  This class is the entry point
 * of the program and contains a controller loop.
 * 
 */
public class Game extends EnvApplet
{
    private boolean finished;
    private Doty doty1;
    private Env env;
    private Room roomLeft, roomRight;
    private Room currentRoom;
    private SimpleBucket bucket;
    private int id;
    private HashMap<String,Doty> dotys;
    private int time;
    private String[] objects;
 
    /**
     * The constructor.  It sets up all the rooms and necessary 
     * objects in each room.
     * 
     */
    public Game()
    {
        id = (int)(Math.random()*100000);
        bucket = new SimpleBucket("URL GOES HERE");
        dotys = new HashMap<String,Doty>();
 
        time = getTime();
 
        roomLeft = new Room(10, 13.001f, 10, "The left room");
        roomRight = new Room(10, 13.001f, 10, "The right room");
 
        roomLeft.setExit("east", roomRight);
        roomLeft.setTextureEast("textures/door.gif");
        roomLeft.addBlock(new Block(1, 1, 4, "Normal Block"));
        roomLeft.addBlock(new Block(4, 1, 8, "Normal Block"));
        roomLeft.addBlock(new Block(7, 1, 3, "Normal Block"));
 
        roomRight.setExit("west", roomLeft);
        roomRight.setTextureWest("textures/door.gif");                
        roomRight.addBlock(new Block(3, 1, 4, "Normal Block"));
        roomRight.addBlock(new Block(5, 1, 2, "Breakable Block"));
        roomRight.addBlock(new Block(6, 1, 8, "Normal Block"));        
 
        doty1 = new Doty(5, 1, 1);
 
    }
 
    /**
     * The play method contains the controller loop.
     */
    public void play()
    {
        finished = false;
 
        // Create a new environment
        env = new Env();
 
        // Starts with roomLeft
        setCurrentRoom(roomLeft);        
        // Adding doty to the environment
        doty1.setRoomDim(currentRoom.getWidth(), currentRoom.getDepth());        
        env.addObject(doty1);
 
        // Position the camera
        env.setCameraXYZ(5, 13, 9);        
        env.setCameraPitch(-75);
 
        // Disable mouse and camera control
        env.setDefaultControl(false);
 
        Thread t = new Thread() {
                public void run() {
                    while(true) {
                        loadGame();
                        time++;
                        saveGame();
                        try {
                            sleep(25);
                        } catch (Exception e) {
                        }
                    }
                }            
            };
 
        t.start();
 
        // The "loop"
        while (finished == false)
        {            
 
            // Ask for user input
            processInput();
 
            // Process the various objects
            checkWall();            
            checkCollision();
 
            // Update the screen
            env.advanceOneFrame(30);
        }
 
        // Just a little cleanup
        env.exit();
    }
 
    /**
     * Helper method for setting the current room to a 
     * particular room.
     * 
     * @param room The room to set the current room to.
     */
    private void setCurrentRoom(Room room)
    {
        if (room != null) {
            currentRoom = room;
            env.setRoom(currentRoom);
            for (Block block : currentRoom.getBlocks()) {
                env.addObject(block);
            }
        }
    }
 
    /**
     * Process the user input
     * 
     */
    private void processInput()
    {        
        // The getKeyDown() method can detect which
        // button is being held down.  Can only detect
        // one button.
        int currentKey = env.getKeyDown();
        int keyUp = env.getKey();
 
        // Reset the display string
        if (currentKey != 0) {
            env.setDisplayStr("");
        }
 
        // Note the use of class constants.  Much more readable!
        if (currentKey == Keyboard.KEY_ESCAPE) {
            finished = true;
        }  else if (currentKey == Keyboard.KEY_UP) {
            doty1.moveZ(-0.1f);
        } else if (currentKey == Keyboard.KEY_DOWN) {
            doty1.moveZ(0.1f);
        } else if (currentKey == Keyboard.KEY_LEFT) {
            doty1.moveX(-0.1f);
        } else if (currentKey == Keyboard.KEY_RIGHT) {
            doty1.moveX(0.1f);
        } else if (currentKey == Keyboard.KEY_L) {
            // This is the "L"ook command.  So we display the description of the room.
            env.setDisplayStr(currentRoom.getDescription());
 
            // If Doty is close to an object, display the description of the object instead.
            for (Block block : currentRoom.getBlocks()) {
                if (doty1.distance(block) <= doty1.getScale()*1.2+block.getScale()) {
                    env.setDisplayStr(block.getDesc());
                }
            }
        }
 
        if (keyUp == Keyboard.KEY_F1) {
            // Popup a about window
            new Popup(this);
        }
        if (keyUp == Keyboard.KEY_F6) {
            // Popup a about window
            loadGame();
        }
    }
 
    private void saveGame() 
    {
        env.setDisplayStr("Time: "+time,2,400);
        try {       
            bucket.write("A"+id,":"+time+":"+doty1.getX()+":"+doty1.getZ()+":"+doty1.getRotateY()+":"+doty1.getRotateX()+":"+currentRoom.getDescription());
            bucket.write("TIME",""+time);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
 
    private void loadGame()
    {
        try {
            objects = bucket.readAll();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);            
        }
        for (String o : objects) {
            if (o.startsWith("A")) {
                String [] elements = o.split(":");
                String did = elements[0].trim();
                int objectTime = Integer.parseInt(elements[1]);
                if (!did.contains("A"+id)) {
                    if (objectTime > time-10 && !dotys.containsKey(did) && elements[6].contains(currentRoom.getDescription())) {
                        Doty doty = new Doty(Float.parseFloat(elements[2]),1,Float.parseFloat(elements[3]));
                        doty.setRotateY(Float.parseFloat(elements[4]));
                        doty.setRotateX(Float.parseFloat(elements[5]));
                        env.addObject(doty);
                        dotys.put(did,doty);
                    } else if (objectTime > time-10 && dotys.containsKey(did) && elements[6].contains(currentRoom.getDescription())) {
                        Doty doty = dotys.get(did);
                        doty.setX(Float.parseFloat(elements[2]));
                        doty.setZ(Float.parseFloat(elements[3]));
                        doty.setRotateY(Float.parseFloat(elements[4]));
                        doty.setRotateX(Float.parseFloat(elements[5]));
 
                    } else {
                        if (dotys.containsKey(did)) {
                            env.removeObject(dotys.get(did));
                            dotys.remove(did);
                        }
                        try {
                            bucket.deleteObject(did);
                        }catch (Exception e) {      
                        }
                    }
                }
            }
            if (o.startsWith("TIME")) {
                time = Integer.parseInt(o.substring(5));
            }
        }
    }
 
    /**
     * Returns the time
     */
    public int getTime()
    {
        int itime = 0;
        try { 
            String time = bucket.read("TIME");
            if (time != "") {
                itime = Integer.parseInt(time);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
        return itime;
    }
 
    /**
     * Check to see if Doty is close to a wall, and exit to the next room if necessary
     */
    private void checkWall()
    {
        if (doty1.getX() > currentRoom.getWidth()-doty1.getScale()) {
            // Going east
            exitTo("east");
        } else if (doty1.getX() < doty1.getScale()) {
            // Going west
            exitTo("west");
        }    else if (doty1.getZ() < doty1.getScale()) {
            // Going west
            exitTo("north");
        }    else if (doty1.getX() > currentRoom.getWidth()-doty1.getScale()) {
            // Going west
            exitTo("south");
        }        
    }
 
    /**
     * A helper method to reduce duplicated code in checkWall
     */
    private void exitTo(String dir)
    {
        if (currentRoom.getExit(dir) != null) {                
            setCurrentRoom(currentRoom.getExit(dir));
            doty1.setRoomDim(currentRoom.getWidth(), currentRoom.getDepth());
            doty1.setExitFrom(dir);           
            env.addObject(doty1);
        } else {
            // Doty has hit a wall
            doty1.revert();
        }
    }
 
    /**
     * Check to see if any collision occur between Doty and the objects in the current room
     */    
    private void checkCollision()
    {
        // For every wall in the current room
        for (Block block : currentRoom.getBlocks()) {
            // Stop doty from moving if doty hits a wall
            if (doty1.distance(block) <= block.getScale()+doty1.getScale()) {                
                doty1.revert();
            }
        }
 
    }
 
    public void incDotySize(double size)
    {
        doty1.setScale(doty1.getScale()+size);
    }
 
    /**
     * The private distance method
     */
    private float distance(float x1, float x2, float y1, float y2, float z1, float z2) {
        float xdiff, ydiff, zdiff;
        xdiff = x2 - x1;
        ydiff = y2 - y1;
        zdiff = z2 - z1;
        return (float) Math.sqrt(xdiff*xdiff + ydiff*ydiff + zdiff*zdiff);
    }    
 
    public static void main (String [] args) {
        (new Game()).play();
    }
 
    class InnerPopup
    {
        JFrame frame;
 
        public InnerPopup()
        {
            frame = new JFrame("About Doty");
            Container contentPane = frame.getContentPane();
            contentPane.add(new JLabel("Doty version 1"), BorderLayout.NORTH);
 
            JButton b = new JButton("Make Bigger");
            b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        doty1.setScale(doty1.getScale()+0.3f);
                    }
                });
 
            contentPane.add(b, BorderLayout.CENTER);
 
            JButton b2 = new JButton("Make Smaller");
            b2.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        doty1.setScale(doty1.getScale()-0.3f);
                    }
                });
            contentPane.add(b2, BorderLayout.SOUTH);
 
            frame.setLocationRelativeTo(null);
            frame.setAlwaysOnTop(true);
            frame.pack();
            frame.setVisible(true);
        }
    }
}