Mouselook and SDL - Code
This is an old article from 2011. I was a kid. I learned a lot since then,
so please do think twice when taking advice from me as a kid.
Okay, here is some code for mouselook with SDL…
struct { int x, y; //In this case: the position where the mouse is held at bool trap; //flag for holding mouse at one place } mouse; void MouseMotion(){ /* Set x and y to the current mouse position */ int x, y; SDL_GetMouseState(&x, &y); int xdiff = x - mouse.x; //Calculate difference in x int ydiff = y - mouse.y; //Calculate difference in y /* rotate camera relative to what it was before */ Cam->relRot( (float) ydiff, (float) xdiff, 0.0f); //Alternative: use gluLookAt(...); // ( xdiff and ydiff are in the right place... comment, if you need explaination) if (mouse.trap){ //Reset Mouse Position to middle of screen SDL_WarpMouse(mouse.x, mouse.y); //Set Cursor } } int main (){ //Initialization...blabla bool done = false; while(!done) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) case SDL_MOUSEMOTION: MouseMotion(); break; //... ther Events ... } //... do other things* } //End }
This code is only a bunch of fragmentsto keep it simple. “Cam” is a camera class I created to handle every camera-related stuff (Position/Rotation…). “RelRot” adds the given vector values to the rotation-vector of the camera. When rendering the sceen, I rotate the Projection Matrix by the rotation-vector of the camera.
btw: this is not exacly the code I use in Mineshooter. I use more classes there ;)
Anyway, I hope this helps somebody out there :)
This post was imported from tumblr