jump algorithm

Started by
May 10, 2025 08:29 PM
1 comment, last by JoeJ 1 month, 2 weeks ago
Advertisement

I want to make my sprite jump like in mario bros.

Is this code a good start?

			Character player;
			player.yVelocity = 0;
			player.isJumping = false;
			player.x = 0;
			player.y = 0;
			//Hack to get window to stay up
			bool quit = false;
			while (quit == false) {
				//Apply the image
				SDL_Rect rect;
				rect.x = 462 + move_sprite;
				rect.y = 686 + player.y;
				SDL_BlitSurface(gHelloWorld_one, &rects[frame], gScreenSurface, &rect);
				frame++;
				if (frame == 10)
				{
					frame = 0;
				}
				SDL_UpdateWindowSurface(gWindow);
				SDL_Event event;
				while (SDL_PollEvent(&event)) {
					if (event.type == SDL_KEYDOWN)
					{
						Uint8 const* keys = SDL_GetKeyboardState(nullptr);
						if (keys[SDL_SCANCODE_ESCAPE] == 1)
						{
							quit = true;
						}
						if (keys[SDL_SCANCODE_SPACE] == 1 && !player.isJumping)
						{
							player.isJumping = true;
							player.yVelocity = JUMP_VELOCITY;
							//quit = true;
						}
						if (keys[SDL_SCANCODE_LEFT] == 1)
						{
							move_sprite--;
						}
						if (keys[SDL_SCANCODE_RIGHT] == 1)
						{
							move_sprite++;
						}
					}
					if (player.isJumping)
					{
						player.yVelocity += GRAVITY;
						player.y += player.yVelocity;
						if (player.y >= 400)
						{
							player.y = 400;
							player.yVelocity = 0;
							player.isJumping = false;
						}
					
					}
				}
			}
		}
	}

pbivens67 said:
Is this code a good start?

Looks good to me.

A few tips:

Do not use integer numbers. Use float. It's not really possible to model acceleration with integers. You need real numbers.
(To do so on 8 bit computers which did not have real numbers, they had emulated it using fixed point math. But that's just unnecessarily complicated today - use floats.)

To be clear, use floats for position (x and y), velocity, and acceleration. (In case you do not use float already, which i can not really tell from the code)

Eventually work on vertical movement first. So the character builds up speed gradually and feels like Mario. That's easier to begin with.
I do this by controlling acceleration, which is a constant value only differing in sign depending on direction. And i cap the velocity by a given max speed, which is higher if the run button is pressed.

For the jump, to give control over jump height the usual trick is to use a smaller acceleration (gravity) value a s long as the jump button is pressed, but switching to a larger value once the button is released.

At least that's how i do those things for typical FPS movement like Quake, which has been adopted from Super Mario.

I want to add that this is not a beginner topic, imo. I recommend to do Pac Man, Space Invaders, or similar games with constant velocity movement first. But good luck anyway!

This topic is closed to new replies.

Advertisement