I am attempting to create a 3D game using solely LWJGL and Slick-util, and I intend for it to be a first-person game, so I need a way to navigate the map using 3D movement. I have a position Vector3f and another vector acc to store acceleration. I have set up the following methods, all bound (in another class) to W, A, S, and D:
public void walkForward()
{
acc.x += walkSpeed * (float) Math.sin(Math.toRadians(yaw)); // Calculations for 3D Movement (please correct me if wrong)
acc.z -= walkSpeed * (float) Math.cos(Math.toRadians(yaw));
}
public void walkBackward()
{
acc.x -= walkSpeed * (float) Math.sin(Math.toRadians(yaw));
acc.z += walkSpeed * (float) Math.cos(Math.toRadians(yaw));
}
public void strafeLeft()
{
acc.x += walkSpeed * (float) Math.sin(Math.toRadians(yaw - 90));
acc.z -= walkSpeed * (float) Math.cos(Math.toRadians(yaw - 90));
}
public void strafeRight()
{
acc.x += walkSpeed * (float) Math.sin(Math.toRadians(yaw + 90));
acc.z -= walkSpeed * (float) Math.cos(Math.toRadians(yaw + 90));
}
Where walkSpeed is a positive float. Also, in my move() method, where movement is actually processed, I have the following:
void move()
{
acc.y = 0.0f; // Keep the player's height stable, for testing purposes.
getPosition().x += acc.x; // Add current velocity to the position.
getPosition().y += acc.y;
getPosition().z += acc.z;
if(acc.x > 0.0f) // Gradually bring player's velocity to 0.
acc.x -= 0.01f;
else if(acc.x < 0.0f)
acc.x += 0.01f;
if(acc.y > 0.0f)
acc.y -= 0.01f;
else if(acc.y < 0.0f)
acc.y += 0.01f;
if(acc.z > 0.0f)
acc.z -= 0.01f;
else if(acc.z < 0.0f)
acc.z += 0.01f;
}
Finally, in the render() method, where transformations are actually made to the game, I have this:
public void render()
{
move();
glRotatef(pitch, 1.0f, 0.0f, 0.0f);
glRotatef(yaw, 0.0f, 1.0f, 0.0f);
glTranslatef(-position.x, -position.y, -position.z);
}
Expected result: Ordinary 3D movement, proper directional motion, etc.
Actual result: Player moves in general direction, speed changes based on both yaw and pitch, releasing all keys (debugging confirms that NO input is being received to the walk() methods causes jittering and strange movement in random directions, whose speed changes based on both yaw and pitch, holding both W + A or W + D causes a massive increase in horizontal speed, etc.
I have a feeling this could be due to missing a pop or push in the matrix, or forgetting to init the identity somewhere. Any help would be appreciated. Thanks in advance!
Methods that manipulate the legacy OpenGL matrix stack, like glRotatef() and glTranslatef(), concatenate the specified transformation with the transformation that is currently on the matrix stack. Since you never reset/restore the transformation, you just keep concatenating more transformations every time render() is called.
To avoid this, you can either reset the transformation before starting to apply the current transformation:
glLoadIdentity();
glRotatef(pitch, 1.0f, 0.0f, 0.0f);
glRotatef(yaw, 0.0f, 1.0f, 0.0f);
glTranslatef(-position.x, -position.y, -position.z);
or save the previous matrix at the start, and restore it at the end:
glPushMatrix();
glRotatef(pitch, 1.0f, 0.0f, 0.0f);
glRotatef(yaw, 0.0f, 1.0f, 0.0f);
glTranslatef(-position.x, -position.y, -position.z);
glPopMatrix();
The second approach has the advantage that it will work correctly if you already had a matrix on the stack (e.g. a view transformation) that you also want to apply, while the first one resets all previous transformations.
Also note that transformations are applied to vertices in the reverse order of being specified. So your transformation sequence will first translate the vertices, then apply the yaw rotation, then the pitch rotation. If that's what you want, it's all good. Otherwise, you'll need to reverse the order.
Related
I am trying to move a triangle in the direction of the top vertex.
Depending on the rotation angle.
This is my code:
private static void render() {
// Clear the pixels on the screen and clear the contents of the depth buffer (3D contents of the scene)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Reset any translations the camera made last frame update
glLoadIdentity();
// Apply the camera position and orientation to the scene
//camera.applyTranslations();
glTranslated(0,0,-5);
glPushMatrix();
glRotated(f.get_direction(),0,0,1);
glTranslated(x,y,0);
f.draw();
glPopMatrix();
x+=(f.get_speed()/30)*cos(f.get_direction()+90);
y+=(f.get_speed()/30)*sin(f.get_direction()+90);
}
The point is that no matter what is the rotation angle that is the direction,
i want to move the triangle according to it.
Did you try to translate according to direction vector but there is simple problem cos and sin arguments is in radians glRotate in degrees:
so we must create static function
static double degToRad(double x)
{
return (x / 180.0) * Math.PI;
}
than use it
glLoadIdenity();
x += Math.cos(degToRad(getDirection() + 90)) * getSpeed();
y += Math.sin(degToRad(getDirection() + 90)) * getSpeed();
glTranslatef(x, y, 0);
glRotatef(getDirection(), 0, 0, 1);
drawObject();
you can also invert direction of movement just subsctacting current angle from 360:
glLoadIdenity();
x += Math.cos(degToRad(360 - getDirection() + 90)) * getSpeed();
y += Math.sin(degToRad(360 - getDirection() + 90)) * getSpeed();
glTranslatef(x, y, 0);
glRotatef(getDirection(), 0, 0, 1);
drawObject();
I'm playing around with creating a small voxel based project with LWJGL. Part of the project is loading small chunks of landscape around the player as they move. The loading part of this works okay, but I ran into an issue where as I walked along the +X axis, the chunks of landscape moving the same distance along the -X axis would load. This would also happen for the Z axis.
I got curious, so I tried reversing the X and Z axis rendering direction on the chunks, which seemed to fix the issue. However, I also decided to render the axis as lines as well, and verify that everything was now drawing correctly, with which I generated the following image:
(I can't embed images apparently, so link: http://i.imgur.com/y5hO1Im.png)
In this image, the red, blue and green lines are drawn along the negative axes, whereas the purple, yellow and cyan lines are drawn along the positive axes. What's really weird about this is that the image is showing that the camera is in the +X and +Z range, but internally, the position vector of the camera is in the -X and -Z range. This would make sense as to why the chunks were loading on the opposite axis, as if the camera was rendering on +X but was internally at a position of -X, then the -X chunks would be loaded instead.
So I'm not sure what's going on here anymore. I'm sure there's a small setting or incorrect positive/negative that I'm missing, but I just can't seem to find anything. So I guess my question is, is the camera rendering correctly with the internal position? If so, do I need to just reverse everything that I render? If not, is there something clearly visible in the camera that is messing up the rendering?
Some snippets of relevant code, trying to not to overflow the post with code blocks
Camera.java
public class Camera {
// Camera position
private Vector3f position = new Vector3f(x, y, z);
// Camera view properties
private float pitch = 1f, yaw = 0.0f, roll = 0.0f;
// Mouse sensitivity
private float mouseSensitivity = 0.25f;
// Used to change the yaw of the camera
public void yaw(float amount) {
this.yaw += (amount * this.mouseSensitivity);
}
// Used to change the pitch of the camera
public void pitch(float amount) {
this.pitch += (amount * this.mouseSensitivity);
}
// Used to change the roll of the camera
public void roll(float amount) {
this.roll += amount;
}
// Moves the camera forward relative to its current rotation (yaw)
public void walkForward(float distance) {
position.x -= distance * (float)Math.sin(Math.toRadians(yaw));
position.z += distance * (float)Math.cos(Math.toRadians(yaw));
}
// Moves the camera backward relative to its current rotation (yaw)
public void walkBackwards(float distance) {
position.x += distance * (float)Math.sin(Math.toRadians(yaw));
position.z -= distance * (float)Math.cos(Math.toRadians(yaw));
}
// Strafes the camera left relative to its current rotation (yaw)
public void strafeLeft(float distance) {
position.x -= distance * (float)Math.sin(Math.toRadians(yaw-90));
position.z += distance* (float)Math.cos(Math.toRadians(yaw-90));
}
// Strafes the camera right relative to its current rotation (yaw)
public void strafeRight(float distance) {
position.x -= distance * (float)Math.sin(Math.toRadians(yaw+90));
position.z += distance * (float)Math.cos(Math.toRadians(yaw+90));
}
// Translates and rotates the matrix so that it looks through the camera
public void lookThrough() {
GL11.glRotatef(pitch, 1.0f, 0.0f, 0.0f);
GL11.glRotatef(yaw, 0.0f, 1.0f, 0.0f);
GL11.glTranslatef(position.x, position.y, position.z);
}
}
Main.java render code
private void render() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glLoadIdentity();
// Set the view matrix to the player's view
this.player.lookThrough();
// Render the visible chunks
this.chunkManager.render();
// Draw axis
GL11.glBegin(GL11.GL_LINES);
// X Axis
GL11.glColor3f(1, 0, 0);
GL11.glVertex3f(-100, 0, 0);
GL11.glVertex3f(0, 0, 0);
GL11.glColor3f(1, 1, 0);
GL11.glVertex3f(0, 0, 0);
GL11.glVertex3f(100, 0, 0);
// Y Axis
GL11.glColor3f(0, 1, 0);
GL11.glVertex3f(0, -100, 0);
GL11.glVertex3f(0, 0, 0);
GL11.glColor3f(0, 1, 1);
GL11.glVertex3f(0, 0, 0);
GL11.glVertex3f(0, 100, 0);
// Z Axis
GL11.glColor3f(0, 0, 1);
GL11.glVertex3f(0, 0, -100);
GL11.glVertex3f(0, 0, 0);
GL11.glColor3f(1, 0, 1);
GL11.glVertex3f(0, 0, 0);
GL11.glVertex3f(0, 0, 100);
GL11.glEnd();
// Render the origin
this.origin.render();
}
chunkManager.render() just iterates through each of the loaded chunks and calls .render() on them, which in turn creates a giant solid cube that is rendered at the origin of the chunk.
More code can be provided if needed.
Replace
GL11.glTranslatef(position.x, position.y, position.z);
with
GL11.glTranslatef(-position.x, -position.y, -position.z);
Think about it, you want to be translating the world to the inverse of where the camera is so that that 0,0,0 is where the camera is.
I am having problem rotating a cube along its own axis and not some arbitrary position. The cube is a collection of other 27 cubes and I have succesfully managed to rotate the group of cubes but not in correct way. I mean when I rotated the cube in x-axis, it makes an orbit around the enter (0,0,0) and not in its own axis. How can i make the cube rotate about its own axis?
public void onDrawFrame(GL10 gl)
{
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
gl.glScalef(0.8f, 0.8f, 0.8f);
int k=0;
gl.glPushMatrix();
gl.glRotatef(cubeRotX, 0.0f, 0.0f , 1.0f);
gl.glRotatef(cubeRotY, 0.0f, 1.0f , 0.0f);
for(int l=0; l<3; l++)
{
if(l == 2) //To rotate only the first front polygon in 1.7f angle
{
gl.glPushMatrix();
gl.glRotatef(rot, 0.0f, 0.0f, 1.0f);
}
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
gl.glPushMatrix();
gl.glTranslatef(-2.1f+(2.1f*i), -2.1f+(2.1f*j), -23.1f+(2.1f*l));
cube[k++].draw(gl);
gl.glPopMatrix();
}
}
if(l ==2)
{
gl.glPopMatrix();
if(rot >= 90.0f)
rot = 90.0f;
else
rot += 4.0f;
}
}
gl.glPopMatrix();
cubeRotX -= 5.0f;
cubeRotY -= 5.0f;
}
To rotate each individual cube, apply a rotation inside the inner glPushMatrix.
EDIT: I missundertood you. More information asked.
After your clarifications:
Load Identity
Apply general transform for all objects
Push matrix
Apply rotation for all child cubes around sun and the sun itself (a general rotation for all cubes around the sun, probably this could be no rotation at all depending on what do you want to archive)
Push matrix
Apply revolution for your "sun".
draw sun
Pop Matrix
For each inner/child cube:
Push matrix
Apply rot
draw cube
pop matrix
Pop Matrix
I have this mouse function in my OpenGL program:
public void mouseInput(){
int mouseX = Mouse.getX();
int mouseY = 600 - Mouse.getY();
int mouseDX = 0, mouseDY = 0;
int lastX = 0, lastY = 0;
mouseDX = mouseX - lastX;
mouseDY = mouseY - lastY;
lastX = mouseX;
lastY = mouseY;
xrot += (float) mouseDX;
yrot += (float) mouseDY;
}
I rotate the "camera" using this code:
glRotatef(xrot, 1.0f, 0.0f, 0.0f);
glRotatef(yrot, 0.f, 1.0f, 0.0f);
And I call the mouseInput() function in the !DisplayIsClosedRequested loop. Currently this causes my game to freak out and my camera rotates all over the place even without me touching the mouse. The cubes I have rendered out also move around the screen randomely. I am using LWJGL, so I cant use any glut functions like glutPassiveMotionFunc(). Can anyone offer help? Basically in summary, my camera is very jerky and rotates the camera in random patterns very fast.
If the camera is rotating even when you are not touching the mouse, you are probably applying the rotation over and over again. You could reset the camera view matrix first (glLoadIdentity() in OpenGL 2 fixed-functionality), every frame, and then apply the rotation. That way you will only rotate from a fixed reference point every frame, instead of the last reference point which was the result of a rotation from a previous frame.
I'm trying to rotate and move a triangle into a certain direction, based on the pointing direction of the triangle. In theory, I calculate the sine and cosine of the direction (0-360 degrees) and add these values to the x- and y-position, right? It just doesn't work.
Also, the triangle should point up in the beginning, not down.
public void speedUp() {
float dirX, dirY;
speed *= acceleration;
if(speed > 50) speed = 50;
println("dir: " + direction + " x: " + cos(direction) + " y: " + sin(direction));
dirX = cos(direction);
dirY = sin(direction);
xPos+=dirX;
yPos+=dirY;
}
public void redraw() {
GL gl = pgl.beginGL(); // always use the GL object returned by beginGL
gl.glTranslatef(xPos, yPos, 0);
gl.glRotatef(direction, 0, 0, 1000);
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor4f(0.1, 0.9, 0.7, 0.8);
gl.glVertex3f(-10, -10, 0); // lower left vertex
gl.glVertex3f( 10, -10, 0); // lower right vertex
gl.glVertex3f( 0, 15, 0); // upper vertex
gl.glEnd();
}
It looks like you need to convert from polar coordinates(moving about using an angle and a radius) to cartesian coordinates(moving about using the x and y).
The formula looks a bit like this:
x = cos(angle) * radius;
y = sin(angle) * radius;
So, as #Lie Ryan mentions, you also need to multiply with speed (which is your radius in polar coordinates).
Either have your angle in degrees but use radians() when using cos,sin as they work with radians, or use radians, and use degrees() with glRotatef, up to you
Also, you might want to have a look at glPushMatrix() and glPopMatrix(). Bascially, they allow you to nest transformations. Whatever transformations you do withing the blocks, they affect just that block locally.
Here's what I mean, use w,a,s,d keys:
import processing.opengl.*;
import javax.media.opengl.*;
float direction = 0;//angle in degrees
float speed = 0;//radius
float xPos,yPos;
void setup() {
size(600, 500, OPENGL);
}
void keyPressed(){
if(key == 'w') speed += 1;
if(key == 'a') direction -= 10;
if(key == 'd') direction += 10;
if(key == 's') speed -= 1;
if(speed > 10) speed = 10;
if(speed < 0) speed = 0;
println("direction: " + direction + " speed: " + speed);
}
void draw() {
//update
xPos += cos(radians(direction)) * speed;
yPos += sin(radians(direction)) * speed;
//draw
background(255);
PGraphicsOpenGL pgl = (PGraphicsOpenGL) g;
GL gl = pgl.beginGL();
gl.glTranslatef(width * .5,height * .5,0);//start from center, not top left
gl.glPushMatrix();
{//enter local/relative
gl.glTranslatef(xPos,yPos,0);
gl.glRotatef(direction-90,0,0,1);
gl.glColor3f(.75, 0, 0);
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex2i(0, 10);
gl.glVertex2i(-10, -10);
gl.glVertex2i(10, -10);
gl.glEnd();
}//exit local, back to global/absolute coords
gl.glPopMatrix();
pgl.endGL();
}
You don't actually need the { } for the push and pop matrix calls, I added them like a visual aid. Also, you can do this without push/pop, by concatenating your transforms, but it's handy to know those are there for your when you need them. Might come in handy when you want to shoot some GL_LINES out of that triangle...pew pew pew!
HTH
You have your units messed up. glRotatef excepts degrees and the trigonometrical functions expect radians. This is the most obvious mistake.
Also, speed is never used in your snippet. I suppose that every frame you're using it somehow, but in the code you pasted there's:
xPos+=dirX
Which is basically "add direction to the position" - not making much sense, unless you want to "move it exactly 1 unit in the given direction instantenously at the moment when speedUp() is called. The usual approach for continous movement would be to:
// each frame:
xPos += dirX * speed * deltaTime;
yPos += dirY * speed * deltaTime;
Try this:
dirX = speed * cos(direction);
dirY = speed * sin(direction);
You are obviously new to OpenGl, so I would recommend you, that you look into quaternions to do your roations. Here are two pretty nice article about this matter: Gamedev and Nehe. I would recommend you to use the Quaternion class from the JMonkeyEngine. Just remove the savable and some other interfaces and you can use them with ease. Here they are located: JMonkey Source
I also use the JME math classes for my own projects. I have already striped most of the dependencies and you can download some classes from here: Volume Shadow. However the Quaternion class is missing, but you WILL need Vector3f :D.