• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
lumia_icy

how to implement a frist-person camera in OpenGL

7 posts in this topic

I am new here and in OpenGL,I wanna implement a first-person camera in OpenGL, but I dont know how to use mouse movement to change the Camera goal,I found that lots of case move the cursor in the center of the screen every time ,I wanna ask is there any other implementation ?Please show me some examples .Thanks![img]http://public.gamedev.net//public/style_emoticons/default/blink.png[/img]
0

Share this post


Link to post
Share on other sites
Hi!
This is a version, which is written in Java using the Lightweight Java Game Library! (LWJGL) :
[source lang="java"]
import java.awt.event.KeyEvent;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.util.glu.GLU;

//First Person Camera Controller
public class BasicFPS
{
//3d vector to store the camera's position in
private Vector3f position = null;
//the rotation around the Y axis of the camera
private float yaw = 0.0f;
//the rotation around the X axis of the camera
private float pitch = 0.0f;
//Constructor that takes the starting x, y, z location of the camera
public BasicFPS(float x, float y, float z)
{
//instantiate position Vector3f to the x y z params.
position = new Vector3f(x, y, z);
}
public BasicFPS() { // This is made so the line FPCameraController app = new FPCameraController(); will work
// TODO Auto-generated constructor stub
}
//increment the camera's current yaw rotation
public void yaw(float amount)
{
//increment the yaw by the amount param
yaw += amount;
}

//increment the camera's current yaw rotation
public void pitch(float amount)
{
//increment the pitch by the amount param
pitch += amount;
}
//moves the camera forward relitive 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 relitive 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 relitive 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 relitive 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 rotate the matrix so that it looks through the camera
//this dose basic what gluLookAt() does
public void lookThrough()
{
//roatate the pitch around the X axis
GL11.glRotatef(pitch, 1.0f, 0.0f, 0.0f);
//roatate the yaw around the Y axis
GL11.glRotatef(yaw, 0.0f, 1.0f, 0.0f);
//translate to the position vector's location
GL11.glTranslatef(position.x, position.y, position.z);
}
private static boolean gameRunning=true;
private static int targetWidth = 800;
private static int targetHeight = 600;

private void init(){
//load textures here and other things
}

private float xrot=0.1f;
private float yrot=0.1f;
private float zrot=0.1f;

/** The texture that’s been loaded */

private static void initDisplay(boolean fullscreen){

DisplayMode chosenMode = null;

try {
DisplayMode[] modes = Display.getAvailableDisplayModes();

for (int i=0;i<modes.length;i++) {
if ((modes[i].getWidth() == targetWidth) && (modes[i].getHeight() == targetHeight)) {
chosenMode = modes[i];
break;
}
}
} catch (LWJGLException e) {
Sys.alert("Error", "Unable to determine display modes.");
System.exit(0);
}

// at this point if we have no mode there was no appropriate, let the user know
// and give up
if (chosenMode == null) {
Sys.alert("Error", "Unable to find appropriate display mode.");
System.exit(0);
}

try {
Display.setDisplayMode(chosenMode);
Display.setFullscreen(fullscreen);
Display.setTitle("Secret Title");
Display.create();

}
catch (LWJGLException e) {
Sys.alert("Error","Unable to create display.");
System.exit(0);
}

}

private static boolean initGL(){
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();

// Calculate the aspect ratio of the window
GLU.gluPerspective(45.0f,((float)targetWidth)/((float)targetHeight),0.1f,100.0f);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();

GL11.glEnable(GL11.GL_TEXTURE_2D); // Enable Texture Mapping ( NEW )
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glClearDepth(1.0f);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
return true;
}
public boolean isKeyPressed(int keyCode) {
// apparently, someone at decided not to use standard

// keycode, so we have to map them over:

switch(keyCode) {
case KeyEvent.VK_SPACE:
keyCode = Keyboard.KEY_SPACE;
break;
case KeyEvent.VK_ESCAPE:
keyCode = Keyboard.KEY_ESCAPE;
break;
case KeyEvent.VK_W:
keyCode = Keyboard.KEY_W;
break;
case KeyEvent.VK_A:
keyCode = Keyboard.KEY_A;
break;
case KeyEvent.VK_S:
keyCode = Keyboard.KEY_S;
break;
case KeyEvent.VK_D:
keyCode = Keyboard.KEY_D;
break;
}

return org.lwjgl.input.Keyboard.isKeyDown(keyCode);
}

private void run(){
BasicFPS camera = new BasicFPS(0, 0, 0);

float dx = 0.0f;
float dy = 0.0f;
float dt = 0.0f; //length of frame
float lastTime = 0.0f; // when the last frame was
float time = 0.0f;

float mouseSensitivity = 0.15f;
float movementSpeed = 10.0f; //move 10 units per second

//hide the mouse
Mouse.setGrabbed(true);
while(gameRunning){
update();
render();
Display.update();

//keep looping till the display window is closed the ESC key is down
/*
while (!Display.isCloseRequested() ||
!Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
{
*/
time = Sys.getTime();

//here is your movement speed, which can be changed to anything
dt = 0.0005f;

lastTime = time;


//distance in mouse movement from the last getDX() call.
dx = Mouse.getDX();
//distance in mouse movement from the last getDY() call.
dy = Mouse.getDY();

//control camera yaw from x movement from the mouse
camera.yaw(dx * mouseSensitivity);
//control camera pitch from y movement from the mouse
camera.pitch(-dy * mouseSensitivity);


//when passing in the distrance to move
//we times the movementSpeed with dt this is a time scale
//so if its a slow frame u move more then a fast frame
//so on a slow computer you move just as fast as on a fast computer

//OVER HERE! What do I do to make the boolean canWalk actually work the right way?

if (Keyboard.isKeyDown(Keyboard.KEY_W))//move forward
{
camera.walkForward(movementSpeed*dt);
}
if (Keyboard.isKeyDown(Keyboard.KEY_S))//move backwards
{
camera.walkBackwards(movementSpeed*dt);
}
if (Keyboard.isKeyDown(Keyboard.KEY_A))//strafe left
{
camera.strafeLeft(movementSpeed*dt);
}
if (Keyboard.isKeyDown(Keyboard.KEY_D))//strafe right
{
camera.strafeRight(movementSpeed*dt);
}

//set the modelview matrix back to the identity
GL11.glLoadIdentity();
//look through the camera before you draw anything
camera.lookThrough();
//you would draw your scene here.

//draw the buffer to the screen
//Display.update();
//}

// finally check if the user has requested that the display be
// shutdown
if (Display.isCloseRequested()) {
gameRunning = false;
Display.destroy();
System.exit(0);
}
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
{
Sys.alert("Close","To continue, press ESCAPE on your keyboard or OK on the screen.");
System.exit(0);

}
}
}

private void update(){
xrot+=0.1f;
yrot+=0.1f;
zrot+=0.1f;
}

private void render(){
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT|GL11.GL_DEPTH_BUFFER_BIT);
//GL11.glLoadIdentity();

GL11.glTranslatef(0.0f,0.0f,-5.0f); // Move Into The Screen 5 Units

GL11.glBegin(GL11.GL_QUADS);
//HERE IS WHERE YOU BIND A TEXTURE
// Front Face
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad

// Back Face
GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f( 1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad

// Top Face
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad

// Bottom Face
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Top Right Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f( 1.0f, -1.0f, -1.0f); // Top Left Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad

// Right face
GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad

// Left Face
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
GL11.glEnd();
}

public static void main(String[] args)
{
BasicFPS main = new BasicFPS();
initDisplay(false);
initGL();
main.init();
main.run();
}
}
[/source]
I hope this will help you!
0

Share this post


Link to post
Share on other sites
I've personally used the solution of treating mouse movements like torque and using the cross product to find out how much it should spin.
0

Share this post


Link to post
Share on other sites
Here's a very simple OpenGL example:

FIrst initialize the camera:
[CODE]
CCamera cam;
cam.position = Vector3D<float>(camX, camY, camZ);
cam.lookAt = Vector3D<float>(0.0,0.0,100.0);
[/CODE]


Then update scene:
[CODE]
void paintGL() {
glClearColor(0.6, 0.8, 0.9, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glLoadIdentity();

//Find current orientation
retning = root->EulerAngle(sensitivity,0,0,root->globalAngle*M_PI/180.0); // Where root is SceneNode
//Set camera a little bit back
cam.position = root->pos - retning*10.0;
//Camera sees at the region before us
cam.lookAt = root->pos + retning*10.0;
//Update camera height
cam.position[2] = cam.position[2] + 100.0;
cam.lookAt[2] = cam.lookAt[2] + 50.0;

drawScene();
swapBuffers();
}
[/CODE]

Now, each time you move your mouse, update global angle:
[CODE]root->globalAngle += sensitivity;[/CODE]
or
[CODE]root->globalAngle -= sensitivity;[/CODE] Edited by Freya
0

Share this post


Link to post
Share on other sites
Also remember that the classic OpenGL tutorials are found on the [url="http://nehe.gamedev.net"]NeHe website[/url].

The one you are looking for is [url="http://nehe.gamedev.net/tutorial/loading_and_moving_through_a_3d_world/22003/"]this one[/url].
0

Share this post


Link to post
Share on other sites
[quote name='Freya' timestamp='1344872510' post='4969096']
Here's a very simple OpenGL example:

FIrst initialize the camera:
[CODE]
CCamera cam;
cam.position = Vector3D<float>(camX, camY, camZ);
cam.lookAt = Vector3D<float>(0.0,0.0,100.0);
[/CODE]


Then update scene:
[CODE]
void paintGL() {
glClearColor(0.6, 0.8, 0.9, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glLoadIdentity();

//Find current orientation
retning = root->EulerAngle(sensitivity,0,0,root->globalAngle*M_PI/180.0); // Where root is SceneNode
//Set camera a little bit back
cam.position = root->pos - retning*10.0;
//Camera sees at the region before us
cam.lookAt = root->pos + retning*10.0;
//Update camera height
cam.position[2] = cam.position[2] + 100.0;
cam.lookAt[2] = cam.lookAt[2] + 50.0;

drawScene();
swapBuffers();
}
[/CODE]

Now, each time you move your mouse, update global angle:
[CODE]root->globalAngle += sensitivity;[/CODE]
or
[CODE]root->globalAngle -= sensitivity;[/CODE]
[/quote]my question is ..how to use my mouse or how to calculate the move?[img]http://public.gamedev.net//public/style_emoticons/default/ph34r.png[/img]
0

Share this post


Link to post
Share on other sites
[quote]my question is ..how to use my mouse or how to calculate the move?[/quote]
Well the other guys post described that before that post.
0

Share this post


Link to post
Share on other sites
Event receivers are usually used to track mouse movements. Those are f.ex. QMouseEvent if you are using QT for graphics, SEvent in Irrlicht and so on.

Code samples for Qt (how to use your mouse): http://www.codeprogress.com/cpp/libraries/qt/qtCaptureMouseMove.php

How to calculate the move: use some variable (sensitivity in my example) for rotation angle. F.eks set sensitivity to 5.0 - it means each time you move your mouse, global angle changes with 5 degrees or smth.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0