I’m having trouble applying some physics to my little Mario style game
I’m trying to write with SDL and VC6.
I’ve been working at this for weeks now. I got the falling works good
and the left/right movement works well too, but I just can’t for the
life of me get the jumping working right:
int RunGame() {
Uint8 *keys;
unsigned int
ticks = SDL_GetTicks(),
ticks_last = ticks,
tick_delta, // Time per Frame.
frame_rate; // Frames per Second.
[…]
// Main Loop.
int done = 0;
while (!done) {
SDL_Event event;
ticks = SDL_GetTicks();
tick_delta = ticks - ticks_last;
[…]
keys = SDL_GetKeyState(NULL);
int moveX = 0, moveY = 0;
// Want to Jump? If you're standing on someting solid, go ahead.
if (!jumping && keys[SDLK_SPACE] && !CanMove(guy, foreground,
dDown, 16711935)) {
velY = max_jump_vel * true_accel;
jumping = true;
}
// Jump.
if (jumping) {
velY -= true_accel;
[Note: CanMove(…) is a function I wrote for collision detection; ]
[ so the player doesn’t go through any barriers. ]
if (velY >= 0) // Going Up.
moveY = CanMove(guy, foreground, dUp, 16711935, velY);
else jumping = false;
//else if (velY < 0) // Finished going Up, now Down.
//moveY = CanMove(guy, foreground, dDown, 16711935, velY);
}
// Stop Jumping, since you've hit a floor.
if (!CanMove(guy, foreground, dDown, 16711935)) {
velY = 0;
jumping = false;
}
// Cieling check.
if (!CanMove(guy, foreground, dUp, 16711935)) {
velY = 0;
jumping = false;
}
// Gravity.
if (!jumping && CanMove(guy, foreground, dDown, 16711935)) {
// You're in the air, so fall.
velY += true_accel;
moveY = CanMove(guy, foreground, dDown, 16711935, velY);
}
// Left / Right Movement.
if (keys[SDLK_LEFT]) {
velX -= true_accel;
if (velX < -walk_max_vel) velX = -walk_max_vel;
moveX = velX > 0 ?
CanMove(guy, foreground, dRight, 16711935, velX) :
CanMove(guy, foreground, dLeft, 16711935, velX);
if (!moveX) velX = 0;
}
if (keys[SDLK_RIGHT]) {
velX += true_accel;
if (velX > walk_max_vel) velX = walk_max_vel;
moveX = velX < 0 ?
CanMove(guy, foreground, dLeft, 16711935, velX) :
CanMove(guy, foreground, dRight, 16711935, velX);
if (!moveX) velX = 0;
}
// Standing. Stopped.
if (!keys[SDLK_LEFT] && !keys[SDLK_RIGHT]) {
// Slow down if theres some leftover velocity.
if (velX < 0) {
velX += true_accel;
moveX = CanMove(guy, foreground, dLeft, 16711935, velX);
}
else if (velX > 0) {
velX -= true_accel;
moveX = CanMove(guy, foreground, dRight, 16711935, velX);
}
}
// Apply Movement & Draw Character.
guyX += moveX;
guyY += moveY;
DrawIMG(guy, guyX, guyY);
SDL_Flip(screen);
[…]
}
}
Thanks for any help and suggestions, and any suggestions to improve any
part of this code are very welcome too. this is the FIRST time I’ve ever
attempted to code this kidna game. I come from a application programming
background, on both win32 and linux, c/c++/Perl/Java. Game programming
is realitively new to me.–
Blaza