Java-Gaming.org Hi !
Featured games (87)
games approved by the League of Dukes
Games in Showcase (670)
Games in Android Showcase (194)
games submitted by our members
Games in WIP (727)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2 3 ... 5
1  Game Development / Game Mechanics / Re: How To Rotate/Position a Camera at a Point on: 2016-03-10 22:45:29
In OpenGL a 4x4 matrix is used to represent a coordinate system. The first three components of the W vector are the origin. The other three vectors of the matrix represent the x, y and z axis. So if your matrix represents the coordinate system of the camera (relative to the world coord. system) then W will be the camera position.
However if it's the other way around and the matrix represents the world coord. system relative to the camera you can either invert that matrix and look at the W vector or you use the Matrix3f.origin method. Both gives you the same result.
There is nothing awkward about it. But it can be confusing to try and keep track of which coord. system is relative to what and which system you are currently using.

And keeping the order of transformations straight is not very difficult. Btw. if you have a scale and a rotation their order doesn't matter.

Let's say we have three transformations A, B and C. And I apply all 3 transformations relative to the world coord. system. i.e. A -> B -> C
Then that is mathematically equivalent to performing the transformations in opposite order C -> B -> A but always relative to the current transformed system.
For example if I want to rotate the camera and than translate it. And both operations should happen relative to the camera than I can instead do those operations in the world coord. system but reverse their order. So I first translate the camera and then rotate it and I don't even have to change the translation vector or rotation quaternion.
2  Discussions / Miscellaneous Topics / Re: How do I get Java and Javascript working together? on: 2016-02-03 16:02:00
There are different options here.
You could change the JavaScript code to make it work in Nashorn.
You could also translate your Java code to JS.
The third option would be to find a way to allow Java and JS to communicate e.g. through XMLHttpRequest or WebSockets.
I suggest you also post your question on stackoverflow, preferably with a more detailed description and example code.
3  Game Development / Newbie & Debugging Questions / Re: How to make the camera move in the direction of the roatation? on: 2016-02-02 04:23:22
I tried to improve the code some more. I defined a class that represents a virtual camera. To move the player around you just have to move the camera, which means your current position is the position of the camera.
Btw. the camera always looks in the direction of the negative z axis (because that's the default in opengl). So moving foward means to move towards -z.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.*;
import com.jogamp.opengl.util.*;
import com.jogamp.opengl.util.gl2.GLUT;
import com.jogamp.opengl.glu.*;
import com.jogamp.opengl.math.*;

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

class Camera {
  private float[] pos = {0, 0, 0};
  private Quaternion orientation = new Quaternion();
 
  void moveTo(float[] pos) {
    this.pos[0] = pos[0];
    this.pos[1] = pos[1];
    this.pos[2] = pos[2];
  }
 
  void move(float[] dv) {
    this.pos[0] += dv[0];
    this.pos[1] += dv[1];
    this.pos[2] += dv[2];
  }
 
  void setOrientation(Quaternion q) {
    orientation.set(q);
    orientation.normalize();
  }
 
  void rotateAbs(Quaternion q) {
    Quaternion temp = new Quaternion();
    temp.set(orientation);
    orientation.set(q);
    orientation.mult(temp);
  }
 
  void rotateRel(Quaternion q) {
    orientation.mult(q);
  }
 
  void rotateXRel(float radians) {
    Quaternion q = new Quaternion();
    q.rotateByAngleX(radians);
    orientation.mult(q);
  }
 
  void rotateYRel(float radians) {
    Quaternion q = new Quaternion();
    q.rotateByAngleY(radians);
    orientation.mult(q);
  }
 
  void rotateZRel(float radians) {
    Quaternion q = new Quaternion();
    q.rotateByAngleZ(radians);
    orientation.mult(q);
  }
 
  void lookAtPos(float[] target, float[] up) {
    float[] direction = new float[3];
    VectorUtil.subVec3(direction, pos, target);
    orientation.setLookAt(direction, up, new float[3], new float[3], new float[3]);
  }
 
  void moveBack(float x) {
    float[] zAxis = orientation.copyMatrixColumn(2, new float[3], 0);
    pos[0] += zAxis[0] * x;
    pos[1] += zAxis[1] * x;
    pos[2] += zAxis[2] * x;
  }
 
  void moveForward(float x) {
    moveBack(-x);
  }
 
  void moveRight(float x) {
    float[] xAxis = orientation.copyMatrixColumn(0, new float[3], 0);
    pos[0] += xAxis[0] * x;
    pos[1] += xAxis[1] * x;
    pos[2] += xAxis[2] * x;
  }
 
  void moveLeft(float x) {
    moveRight(-x);
  }
 
  void prepareGL(GL2 gl) {
    float[] axis = new float[3];
    float angle = orientation.toAngleAxis(axis);
    gl.glRotated(-Math.toDegrees(angle), axis[0], axis[1], axis[2]);
    gl.glTranslated(-pos[0], -pos[1], -pos[2]);
  }
}

public class Rotation2 extends JFrame implements GLEventListener, KeyListener
{
    GLCanvas canvas = null;
    Animator an;
   
    public Rotation2()
    {
        canvas=new GLCanvas();
        an=new Animator(canvas);
        add(canvas);
        canvas.addGLEventListener(this);
        canvas.addKeyListener(this);
        setSize(1280,900);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        an.start();
        requestFocus();
       
    }
   
    Camera cam = new Camera();
   
    float red = 0;
    float green = 0;
    float blue = 1;
   
    public void init(GLAutoDrawable drawable)
    {  
        GL2 gl = drawable.getGL().getGL2();
        GLU glu = new GLU();
        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glLoadIdentity();
       
        double w = drawable.getSurfaceWidth();
        double h = drawable.getSurfaceHeight();
        double aspect = w/h;
        glu.gluPerspective(60.0, aspect, 2.0, 200.0);
        cam.moveBack(30);
       
    }
   
    public void display(GLAutoDrawable drawable)
    {
        GL2 gl=drawable.getGL().getGL2();
        GLU glu = new GLU();
        GLUT glut = new GLUT();
       
        gl.glMatrixMode(GL2.GL_MODELVIEW);
        gl.glLoadIdentity();
       
        gl.glClearColor(0f,0f,0f,0f);
       
        cam.prepareGL(gl);
       
        gl.glClear(GL2.GL_COLOR_BUFFER_BIT);
       
        gl.glColor3f(1, 1, 1);
        gl.glBegin(GL2.GL_QUADS);
        gl.glVertex3i(0, 100, -500);
        gl.glVertex3i(0, 100, 0);
        gl.glVertex3i(500, 100, 0);
        gl.glVertex3i(500, 100, -500);
        gl.glEnd();
       
        red = 0.0f;
        green = 0.0f;
        blue = 0.9f;
        gl.glColor3f(red, green, blue);
//transforming the place the next shape
//will be drawn.
        gl.glTranslated(2, 0, 2);
//We use wire here because default
//lighting is not good enough to
//use when rendering the solid version
        glut.glutWireIcosahedron();
//more shapes to navigate through
        gl.glTranslated(-4, 0, 0);
        glut.glutWireIcosahedron();
        red = 0.0f;
        green = 0.9f;
        blue = 0.1f;
        gl.glColor3f(red, green, blue);
        gl.glTranslated(4, 0, 4);
        glut.glutWireIcosahedron();
        gl.glTranslated(-4, 0, 0);
        glut.glutWireIcosahedron();
        red = 0.9f;
        green = 0.0f;
        blue = 0.1f;
        gl.glColor3f(red, green, blue);
        gl.glTranslated(4, 0, 4);
        glut.glutWireIcosahedron();
        gl.glTranslated(-4, 0, 0);
        glut.glutWireIcosahedron();
        red = 0.9f;
        green = 0.0f;
        blue = 0.9f;
        gl.glColor3f(red, green, blue);
        gl.glTranslated(4, 0, 4);
        glut.glutWireIcosahedron();
        gl.glTranslated(-4, 0, 0);
        glut.glutSolidIcosahedron();
       
        gl.glBegin(GL2.GL_QUADS);
        // Right-face
        gl.glColor3f(100.0f, 0.0f, 100.0f); // violet
        gl.glVertex3f(100.0f, 100.0f, -100.0f);
        gl.glVertex3f(100.0f, 100.0f, 100.0f);
        gl.glVertex3f(100.0f, -100.0f, 100.0f);
        gl.glVertex3f(100.0f, -100.0f, -100.0f);
       
        gl.glEnd();
       
    }
   
    public void reshape(GLAutoDrawable drawable,int x,int y,int width,int height)
    {}
    public void dispose(GLAutoDrawable drawable)
    {}
   
   
    public static void main(String[] ar)
    {
        new Rotation2();
    }
   
    @Override
    public void keyTyped(KeyEvent e) {
    }
   
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_W) {
          cam.moveForward(1);
        }
        else if (e.getKeyCode() == KeyEvent.VK_S) {
          cam.moveBack(1);
        }
        else if(e.getKeyCode() == KeyEvent.VK_A) {
          cam.moveLeft(1);
        }
        else if (e.getKeyCode() == KeyEvent.VK_D) {
          cam.moveRight(1);
        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
          cam.rotateYRel((float)Math.toRadians(-5));
        }
        else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
          cam.rotateYRel((float)Math.toRadians(5));
        }
        else if (e.getKeyCode() == KeyEvent.VK_UP) {
          cam.rotateXRel((float)Math.toRadians(5));
        }
        else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
          cam.rotateXRel((float)Math.toRadians(-5));
        }
       
        canvas.repaint();
    }
   
    @Override
    public void keyReleased(KeyEvent e) {
       
    }
}
4  Game Development / Newbie & Debugging Questions / Re: How to make the camera move in the direction of the roatation? on: 2016-01-30 15:31:31
I don't have much experience with OpenGL but I played around with your code a bit and it looks like I got it to work.
But of course this code is still very crude.
btw. the imports are different because I used the latest version of jogl. Just change them back to match your version.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.*;
import com.jogamp.opengl.util.*;
import com.jogamp.opengl.util.gl2.GLUT;
import com.jogamp.opengl.glu.*;
import com.jogamp.opengl.math.Quaternion;


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Rotation2 extends JFrame implements GLEventListener, KeyListener
{
    GLCanvas canvas = null;
    Animator an;
   
    public Rotation2()
    {
        canvas=new GLCanvas();
        an=new Animator(canvas);
        add(canvas);
        canvas.addGLEventListener(this);
        canvas.addKeyListener(this);
        setSize(1280,900);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        an.start();
        requestFocus();
       
    }
    float xPosition = 0;
    float yPosition = 0;
    float zPosition = 0;
   
    Quaternion cameraOrientation = new Quaternion();
   
    float red = 0;
    float green = 0;
    float blue = 1;
   
   
    public void init(GLAutoDrawable drawable)
    {  
        GL2 gl = drawable.getGL().getGL2();
        GLU glu = new GLU();
        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glLoadIdentity();
       
        double w = drawable.getSurfaceWidth();
        double h = drawable.getSurfaceHeight();
        double aspect = w/h;
        glu.gluPerspective(60.0, aspect, 2.0, 200.0);
       
    }
    double yRot = 0;
    double xRot = 0;
   
    public void display(GLAutoDrawable drawable)
    {
        GL2 gl=drawable.getGL().getGL2();
        GLU glu = new GLU();
        GLUT glut = new GLUT();
       
        gl.glMatrixMode(GL2.GL_MODELVIEW);
        gl.glLoadIdentity();
       
        gl.glClearColor(0f,0f,0f,0f);
       
        gl.glRotated(xRot, 1, 0, 0);
        gl.glRotated(yRot, 0, 1, 0);
        gl.glTranslated(xPosition, yPosition, zPosition);
       
       
        gl.glTranslated(0, 0, -30);
       
        gl.glClear(GL2.GL_COLOR_BUFFER_BIT);
       
        gl.glColor3f(1, 1, 1);
        gl.glBegin(GL2.GL_QUADS);
        gl.glVertex3i(0, 100, -500);
        gl.glVertex3i(0, 100, 0);
        gl.glVertex3i(500, 100, 0);
        gl.glVertex3i(500, 100, -500);
        gl.glEnd();
       
        red = 0.0f;
        green = 0.0f;
        blue = 0.9f;
        gl.glColor3f(red, green, blue);
//transforming the place the next shape
//will be drawn.
        gl.glTranslated(2, 0, 2);
//We use wire here because default
//lighting is not good enough to
//use when rendering the solid version
        glut.glutWireIcosahedron();
//more shapes to navigate through
        gl.glTranslated(-4, 0, 0);
        glut.glutWireIcosahedron();
        red = 0.0f;
        green = 0.9f;
        blue = 0.1f;
        gl.glColor3f(red, green, blue);
        gl.glTranslated(4, 0, 4);
        glut.glutWireIcosahedron();
        gl.glTranslated(-4, 0, 0);
        glut.glutWireIcosahedron();
        red = 0.9f;
        green = 0.0f;
        blue = 0.1f;
        gl.glColor3f(red, green, blue);
        gl.glTranslated(4, 0, 4);
        glut.glutWireIcosahedron();
        gl.glTranslated(-4, 0, 0);
        glut.glutWireIcosahedron();
        red = 0.9f;
        green = 0.0f;
        blue = 0.9f;
        gl.glColor3f(red, green, blue);
        gl.glTranslated(4, 0, 4);
        glut.glutWireIcosahedron();
        gl.glTranslated(-4, 0, 0);
        glut.glutSolidIcosahedron();
       
        gl.glBegin(GL2.GL_QUADS);
        // Right-face
        gl.glColor3f(100.0f, 0.0f, 100.0f); // violet
        gl.glVertex3f(100.0f, 100.0f, -100.0f);
        gl.glVertex3f(100.0f, 100.0f, 100.0f);
        gl.glVertex3f(100.0f, -100.0f, 100.0f);
        gl.glVertex3f(100.0f, -100.0f, -100.0f);
       
        gl.glEnd();
       
    }
   
    public void reshape(GLAutoDrawable drawable,int x,int y,int width,int height)
    {}
    public void dispose(GLAutoDrawable drawable)
    {}
   
   
    public static void main(String[] ar)
    {
       
        new Rotation2();
    }
   
    @Override
    public void keyTyped(KeyEvent e) {
       
    }
   
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_W) {
            float[] zAxis = cameraOrientation.copyMatrixColumn(2, new float[3], 0);
            xPosition += zAxis[0];
            yPosition += zAxis[1];
            zPosition += zAxis[2];
        }
        else if (e.getKeyCode() == KeyEvent.VK_S) {
            float[] zAxis = cameraOrientation.copyMatrixColumn(2, new float[3], 0);
            xPosition -= zAxis[0];
            yPosition -= zAxis[1];
            zPosition -= zAxis[2];
        }
        else if(e.getKeyCode() == KeyEvent.VK_A) {
            float[] xAxis = cameraOrientation.copyMatrixColumn(0, new float[3], 0);
            xPosition += xAxis[0];
            yPosition += xAxis[1];
            zPosition += xAxis[2];
        }
        else if (e.getKeyCode() == KeyEvent.VK_D) {
            float[] xAxis = cameraOrientation.copyMatrixColumn(0, new float[3], 0);
            xPosition -= xAxis[0];
            yPosition -= xAxis[1];
            zPosition -= xAxis[2];
        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            yRot+=5;
        }
        else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            yRot-=5;
        }
        else if (e.getKeyCode() == KeyEvent.VK_UP) {
            xRot-=5;
        }
        else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            xRot+=5;
        }
        cameraOrientation = new Quaternion();
        cameraOrientation.rotateByAngleY((float)Math.toRadians(-yRot));
        cameraOrientation.rotateByAngleX((float)Math.toRadians(-xRot));
       
        canvas.repaint();
    }
   
    @Override
    public void keyReleased(KeyEvent e) {
       
    }
}
5  Discussions / Miscellaneous Topics / Re: How memory works? on: 2014-11-17 05:34:22
I just wanted to know the answer to a question that was on my mind...
Btw, thx for answering...
So if I understand you correctly you don't want to understand this topic thoroughly but you just want a quick and simple answer?
In that case it's enough to concentrate on the stack. There is a stack pointer (SP) in a CPU register. The stack pointer is an address into memory (the location of the stack which is simply an array that grows backwards). Every time you store something on the stack the SP get's decremented and the value stored at the location the SP points to. When a program requests memory from the OS it get's a pointer to that memory location and can then store that pointer on the stack. So you could say that you have one single pointer (the SP) that allows you to store and retrieve all the other pointers.
6  Discussions / Miscellaneous Topics / Re: How memory works? on: 2014-11-15 23:54:37
If you want to truly understand how this stuff works you need to learn assembler and write some (small simple) programs in it. Looking at C and what kind of assembler code a C compiler produces helps too.
I recommend you work through Computer Science 61C
https://www.youtube.com/watch?v=flQuXQQaYE8&t=0s&list=PL-XXv-cvA_iDHtKXLFJbDG-i6L9oDr5X9
It explains everything.
7  Java Game APIs & Engines / OpenGL Development / Re: [LWJGL] Making The Camera Look At A Point on: 2014-11-15 23:27:39
You have to invert the matrix because you defined it the wrong way around.
As I already mentioned, the first index is the row and the second the column.
Switching rows and columns is inverting the matrix.
That means the correct way of defining the matrix would be
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
         Matrix4f matrix = new Matrix4f();
         matrix.m00 = side.x;
         matrix.m10 = side.y;
         matrix.m20 = side.z;
         matrix.m01 = up.x;
         matrix.m11 = up.y;
         matrix.m21 = up.z;
         matrix.m02 = -forward.x;
         matrix.m12 = -forward.y;
         matrix.m22 = -forward.z;
8  Game Development / Newbie & Debugging Questions / Re: Image Effects on: 2014-10-31 01:20:14
A search for "image pixel filter"
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=image%20pixel%20filter
gives many interesting results
e.g.
http://lodev.org/cgtutor/filtering.html
http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
http://tavmjong.free.fr/INKSCAPE/MANUAL/html/Filters-Pixel.html
https://processing.org/tutorials/pixels/

Also useful are affine transforms for scaling, shearing, rotating, etc.
http://en.wikipedia.org/wiki/Affine_transformation
http://docs.oracle.com/javase/7/docs/api/java/awt/geom/AffineTransform.html
9  Java Game APIs & Engines / OpenGL Development / Re: [LWJGL] Making The Camera Look At A Point on: 2014-10-29 02:24:17
Why do you set the third column of the matrix to -forward instead of +forward?
And why do you call the third column m20, m21, m22. The index of the row is usually given first. Although I guess it doesn't really matter.
Also the equations I gave you calculate the absolute yaw and pitch, not the change.
It's also possible that yawn or pitch has the wrong sign and needs to be negated.
10  Game Development / Game Mechanics / Re: Flexible event-trigger system on: 2014-10-28 16:52:36
How many millions of users are you expecting?
I don't think you need a separate thread.
Add event listeners to your game objects that get notified when something happens. You can add and remove event listeners while a program is running.
11  Java Game APIs & Engines / OpenGL Development / Re: [LWJGL] Making The Camera Look At A Point on: 2014-10-28 16:44:01
I didn't test it but I think this should work.

forward = third column of the matrix as a vector

forward2 = forward.copy();
forward2.y = 0;
forward2.normalise();
yawn = Math.atan2(forward2.z, forward2.x);
pitch = Math.acos(forward.copy().dotProduct(forward2));
12  Discussions / Miscellaneous Topics / Re: Calculating points in a circle on: 2014-10-26 14:58:02
Why do you want to use a circle?
If you need pixel perfect collision detection the simplest approach is to use rectangles.
You have a big array that contains all the pixels of the terrain and another array that contains all the pixels of your worm. Then you can just go through the arrays and check if there are two pixels at the same spot.
To make this faster you can use bit masks. Which means that each entry in the array is an integer number and each bit in that number represents one pixel. You can then use xor to test for overlapping pixels.
13  Game Development / Game Mechanics / Re: Vectors and Reflection - Ball bouncing messed up by simultaneous collisions? on: 2014-07-16 00:45:59
Process only one object at a time. Move it, check for collisions, move it back if necessary. Make sure the game is in a valid state at the end of that process i.e. nothing overlaps. Only then go on to the next object.
14  Game Development / Newbie & Debugging Questions / Re: Generate random path on a 5x5 on: 2014-07-14 18:35:45
I added some comments to the code.
You could also read this to help you understand backtracking better.
http://en.wikipedia.org/wiki/Backtracking
15  Game Development / Newbie & Debugging Questions / Re: Generate random path on a 5x5 on: 2014-07-14 17:37:54
You definitely need backtracking if the path is much longer then 5.
e.g. Try to find a random path of length 25 on a 5x5 board. If you always discard the entire path once you reach a dead end, it's gonna take forever to get a solution.
Backtracking only discards as much of the path as necessary and is therefore much faster.
Here is the most simple backtracking algorithm I could come up with to solve your problem.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RandomPath {
  static int[][] matrix = new int[5][5];
  static List<int[]> movements = Arrays.asList(
    new int[] {1, 0}, //right
    new int[] {-1, 0}, //left
    new int[] {0, 1}, //down
    new int[] {0, -1}); //up
 
  public static void main(String[] args) {
    //a list of all the possible start positions
    ArrayList<int[]> startPositions = new ArrayList<>();
    for(int x = 0; x < matrix.length; x++) {
      for(int y = 0; y < matrix[0].length; y++) {
        startPositions.add(new int[] {x, y});
      }
    }
    Collections.shuffle(startPositions);
    for(int[] pos: startPositions) {
      if(findPath(pos[0], pos[1], 25, 1)) break;
    }
    printMatrix();
  }
 
  static void printMatrix() {
    for(int y = 0; y < matrix[0].length; y++) {
      for(int x = 0; x < matrix.length; x++) {
        if(x > 0) System.out.print(",");
        if(matrix[x][y] < 10) System.out.print(" ");
        System.out.print(matrix[x][y]);
      }
      System.out.println();
    }
  }
 
  //recursive method that uses backtracking to find a path
  //x, y: where to go next
  //maxN: target length of path
  //n: current length (actually the length of the path once x,y has been set to n)
  //returns true if a path has been found
  static boolean findPath(int x, int y, int maxN, int n) {
    //if x,y is outside the matrix or it's already part of the path we can return false
    if(x < 0 || x >= matrix.length ||
       y < 0 || y >= matrix[0].length || matrix[x][y] != 0) return false;
    matrix[x][y] = n;
    if(n == maxN) return true; // target length reached
    Collections.shuffle(movements);
    for(int[] move: movements) {
      if(findPath(x + move[0], y + move[1], maxN, n+1)) return true;
    }
    //if no path was found we backtack
    //i.e. we remove x, y from the path and return false
    matrix[x][y] = 0;
    return false;
  }
}
16  Game Development / Newbie & Debugging Questions / Re: Breaking a bullet's velocity into components on: 2014-06-21 23:33:48
Are you sure that angle is in radians?
17  Game Development / Shared Code / Re: json on: 2014-05-23 14:53:21
Here is another JSON parser. It's a recursive descent parser and should be able to handle all standard json code.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
import java.util.*;
import java.io.*;

class JSON {
    static LinkedList<Object> tokenize(Scanner in) {
        LinkedList<Object> list = new LinkedList<>();
        while(true) {
            in.skip("\\s*");
            String token = in.findWithinHorizon(",|:|\\[|\\]|\\{|\\}|\".*?\"|'.*?'|true|false|null|\\d*\\.\\d*|\\d+", 0);
            if(token == null) {
                if(in.hasNext()) throw new RuntimeException();
                else return list;
            }
            char c = token.charAt(0);
            if(c == '"' && token.endsWith("\"") || c == '\'' && token.endsWith("'")) list.add(token.substring(1, token.length()-1));
            else if(c >= '
0' && c <= '9' || c == '.' ) list.add(Double.valueOf(token));
            else if(token.equalsIgnoreCase("true") || token.equalsIgnoreCase("false")) list.add(Boolean.valueOf(token));
            else if(token.equalsIgnoreCase("null")) list.add(null);
            else list.add(token);
        }
    }
   
    static Object parseValue(LinkedList<Object> tokens) {
        Object elem = tokens.pop();
        if(elem.equals("{")) return parseJSON(tokens);
        else if(elem.equals("[")) return parseArray(tokens);
        else return elem;
    }
   
    static List<Object> parseArray(LinkedList<Object> tokens) {
        ArrayList<Object> list = new ArrayList<>();
        if(tokens.peek().equals("]")) {tokens.pop(); return list;}
        while(true) {
            list.add(parseValue(tokens));
            Object elem = tokens.pop();
            if(elem.equals("]")) return list;
            else if(!elem.equals(",")) throw new RuntimeException();
        }
    }
   
    static Map<String, Object> parseJSON(LinkedList<Object> tokens) {
        HashMap<String, Object> map = new HashMap<>();
        if(tokens.peek().equals("}")) {tokens.pop(); return map;}
        while(true) {
            String key = (String)tokens.pop();
            if(!tokens.pop().equals(":")) throw new RuntimeException();
            Object value = parseValue(tokens);
            map.put(key, value);
            Object elem = tokens.pop();
            if(elem.equals("}")) return map;
            else if(!elem.equals(",")) throw new RuntimeException();
        }
    }
   
    static Map<String, Object> parseJSON(Scanner in) {
        LinkedList<Object> tokens = tokenize(in);
        if(!tokens.pop().equals("{")) throw new RuntimeException();
        return parseJSON(tokens);
    }
   
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("test.json"));
        Map<String, Object> map = parseJSON(in);
        in.close();
        System.out.println(map);
       
    }
}
18  Game Development / Newbie & Debugging Questions / Re: Calculating probabilities - is this the right way? on: 2014-05-17 17:28:09
If you run the code a few times you'll notice that you don't get a consistent output distribution of 50%. You are just as likely to get 0,0 or 1,1 as you are to get the desired output of 0,1 or 1,0.

Which is exactly the behaviour we want. So no bug here. If you always got 0,1 or 1,0 it wouldn't be very random.
19  Game Development / Newbie & Debugging Questions / Re: Calculating probabilities - is this the right way? on: 2014-05-17 10:43:45
Here is a more flexible solution.
It has two advantages over many other proposals.
You can list the elements in any arbitrary order and you can easily add e.g. some slider controls to change the probabilities while the program is running, because you don't put the numbers directly into the list but instead you put a function in there that can reference e.g. a JSlider or some other source of numbers.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
Supplier[] probabilities = {
    () -> 50, () -> new A(),
    () -> 10, () -> new B(),
    () -> 35, () -> new C(),
    () ->  5, () -> new D()
};
RandomGenerator rg = new RandomGenerator(probabilities);
HashMap<Class, Integer> map = new HashMap<>();

for(int i = 0; i < 100000; i++) {
    Object o = rg.next();
    map.merge(o.getClass(), 1, (oldNum, x) -> oldNum + 1);
}

System.out.println(map);


Here is the rest of the code
http://pastebin.com/xP1EMLBR
20  Game Development / Game Mechanics / Re: [Math] Kinetic energy of impact between two moving objects on: 2014-05-11 10:55:57
My calculations are based on both, momentum and energy.
I calculate the energy lost in the collision.

before collision: 1/2 * 0^2  + 1/2 * 20^2 = 200 J
after collision:   1/2 * 10^2 + 1/2 * 10^2 = 100 J

So 100 J were lost on the collision. And that number is independant of the reference frame.
21  Game Development / Game Mechanics / Re: Moving the camera in 3D space on: 2014-05-11 10:39:11
I don't have the code for camera.rotate but you probably rotate relative to the game coordinate system instead of the camera coordinate system. You just need to reverse the order of operations i.e. apply the matrix/quaternion of the camera to the rotation matrix/quaternion, not the other way around.
22  Game Development / Game Mechanics / Re: [Math] Kinetic energy of impact between two moving objects on: 2014-05-11 06:53:50
I wrote some code that collides two objects 100 times in different random reference frames and calculates the kinetic energy lost in the collision. As expected it gets the same result each time so it really is independant of the reference frame.

http://pastebin.com/dzvxs6RC
23  Game Development / Game Mechanics / Re: [Math] Kinetic energy of impact between two moving objects on: 2014-05-09 04:24:22
Here is a more detailed explanation
http://en.wikipedia.org/wiki/Non-inertial_reference_frame

In short, just don't use an accelerated object as your reference.

The damage caused by a collision depends on the energy dissipated which is the kinetic energy befrore the collision minus the energy after the collision.
24  Game Development / Game Mechanics / Re: [Math] Kinetic energy of impact between two moving objects on: 2014-05-09 03:49:36
If you look at this from the point of view of one of the objects you are dealing with an accelerated frame of reference which behaves in a more complex way than a normal unaccelerated frame of reference. So I suggest you always use absolute velocities (i.e. velocities relativ to your game coordinate system).
Also after the collision the two objects might still be moving. You have to calculate the difference of the total energy before and after the collision.
25  Java Game APIs & Engines / OpenGL Development / Re: Design or pattern for handling background consumer/producer tasks on: 2014-05-08 19:19:09
Java 8 introduced the CompletableFuture class. With that you can do this kind of stuff very easily.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
static Image loadImage(String path) {
}
static Texture allocateTexture() {
}
static void uploadTexture(Image image, Texture texture) {
}
...
CompletableFuture<Image> image = CompletableFuture.supplyAsync(() -> loadImage(path));
CompletableFuture<Texture> texture = CompletableFuture.supplyAsync(() -> allocateTexture());
image.thenAcceptBothAsync(texture, (Image im, Texture tx) -> uploadTexture(im, tx));


Of course you could also have your loadImage method return a CompletableFuture<Image> instead of an Image to shorten the rest of the code.
And by the way - using CompletableFutures in this way will never block a thread. So it will work fine even if you have a million tasks.
26  Discussions / General Discussions / Re: [Web Games] What is the best second language? on: 2014-05-01 18:00:41
You could also use Scala. The Scala.JS project looks very promising. I played around with it and the js files it produces are about the same size as in Dart, the performance is similar too.
You can try it out interactively here
http://www.scala-js-fiddle.com/

The big advantage here is that you can run your Scala code either on the JVM or compile it to JS and run it in the browser.
27  Discussions / General Discussions / Re: [Web Games] What is the best second language? on: 2014-05-01 01:47:34
For someone who is used to Java, Dart is indeed the easiest way to get into web development. It's kind of a mix between Java and JavaScript. Nonetheless it still makes sense to learn JavaScript first since you need to be able to use a JS game engine from within Dart.
28  Discussions / Miscellaneous Topics / Re: Is our Universe Simulatable? on: 2014-04-21 02:08:58
Let's assume that we had a simulated universe running on a computer. A fully deterministic universe without any quantum randomness.
We have an initial state S and a function f that transforms the current state into a future state. f contains therefore the complete laws of physics of that universe.
That means any event that ever happens is fully determined by S and f alone and completely independant of the computer.
One question here is - what happens when intelligent beings evolve in that simulation? They would not be able to determine if they are simulated or not.
Again - anything that happens depends on S and f alone. So they couldn't possibly build an instrument that measures anything that isn't derived from S or f like for example the computer or the outside world.
The paradoxical thing about this is - Even if they somehow came to the believe that they are simulated, they wouldn't be able to tell whether the simulation is running or not, or whether it ever run at all. Because that information is not contained in either S or f.
29  Game Development / Game Mechanics / Re: Mathematical curves. on: 2014-04-20 20:47:54
I would use 1 - (1-x)^3
http://www.wolframalpha.com/input/?i=1+-+%281-x%29%5E3%2C+x+%3D+0+to+1

It's perfectly horizontal at 1,1
30  Discussions / General Discussions / Re: Get position of end of angle? on: 2014-04-19 02:01:09
I remember seeing a post by wessles some where where he got awnsers to how to find the end of his gun on his very first submission, but i cant find it. Any one else?
Do you mean this thread?
http://www.java-gaming.org/topics/calculating-certain-points-after-rotating-an-image/26744/msg/236014/view.html
Pages: [1] 2 3 ... 5
 
IanParcs (36 views)
2016-04-18 14:18:53

KaiHH (36 views)
2016-04-18 08:35:41

KaiHH (67 views)
2016-04-15 12:43:58

theagentd (67 views)
2016-04-14 02:16:17

theagentd (74 views)
2016-04-14 02:15:43

IanParcs (67 views)
2016-04-12 03:51:16

IanParcs (37 views)
2016-04-12 03:50:03

IanParcs (33 views)
2016-04-12 03:49:54

IanParcs (30 views)
2016-04-12 03:49:52

IanParcs (39 views)
2016-04-12 03:49:52
Website offering 3D Models specifically for games for free
by vusman
2016-04-29 12:56:17

List of Learning Resources
by SilverTiger
2016-02-05 09:39:47

List of Learning Resources
by SilverTiger
2016-02-05 09:38:38

List of Learning Resources
by SilverTiger
2016-02-05 09:35:50

Rendering resources
by Roquen
2015-11-13 14:37:59

Rendering resources
by Roquen
2015-11-13 14:36:58

Math: Resources
by Roquen
2015-10-22 07:46:10

Networking Resources
by Roquen
2015-10-16 07:12:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!