Mouselook and SDL - Code

This is an old ar­ti­cle from 2011. I was a kid. I learned a lot since then, so please do think twice when tak­ing ad­vice 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 on­ly a bunch of frag­mentsto keep it sim­ple. “Cam” is a cam­era class I cre­at­ed to han­dle ev­ery cam­era-re­lat­ed stuff (Po­si­tion/Ro­ta­tion…). “Rel­Rot” adds the giv­en vec­tor val­ues to the ro­ta­tion-vec­tor of the cam­era. When ren­der­ing the sceen, I ro­tate the Pro­jec­tion Ma­trix by the ro­ta­tion-vec­tor of the cam­era.

btw: this is not ex­a­cly the code I use in Mi­neshoot­er. I use more class­es there ;)

Any­way, I hope this helps some­body out there :)

This post was im­port­ed from tum­blr

Tumblr

Archived blog posts from squareys.tum­blr.com.