4 ms·
This can also sometimes be achieved with math. For example, I was writing code that handled velocity and animation based on the arrow keys. The character had to
by AndyKelley 18y ago
This can also sometimes be achieved with math. For example, I was writing code that handled velocity and animation based on the arrow keys. The character had to change animations depending on 8 directions - nesw & diagonals. At first I had an ugly if-elseif statement handling all the keystates. But then I realized I could come up with a cool scheme to simplfy and beautify the code. I also needed to solve the problem of having a constant max-velocity that stayed the same even when going in a diagonal.
//which direction to go
dirX = 0;
dirY = 0;
if( keystate[SDLK_LEFT] ) dirX--;
if( keystate[SDLK_RIGHT]) dirX++;
if( keystate[SDLK_UP] ) dirY--;
if( keystate[SDLK_DOWN]) dirY++;
if( dirX == 0 && dirY == 0){
//stand still
heroVelX = 0;
heroVelY = 0;
heroAnimation = heroStill[oldHeroDirIndex];
} else {
//run in a direction
angle = atan2(dirY,dirX);
heroVelX = heroSpeed * cos(angle);
heroVelY = heroSpeed * sin(angle);
oldHeroDirIndex = (dirX+1)*3 + (dirY+1);
heroAnimation = heroRunning[oldHeroDirIndex];
}
//step to next frame in animation
if( ++heroAnimation->curFrame >= heroAnimation->numFrames ) heroAnimation->curFrame = 0;
heroX += heroVelX;
heroY += heroVelY;
-removes conflict from pressing left and right or up and down at the same time
-uses a formula to calculate which animation to use, instead of using switch statement
-uses a little bit of trig to keep max-speed constant
Programming like this is very rewarding, if only for the feeling you get when it works. I guess this isn't really a big deal to any of you, but this sucker used to be 70 repetitive and buggy lines, rather than the pretty 29 it is now.