SDL2.0 Character Jumping & Gravity

Started by
2 comments, last by Lactose 9 years, 4 months ago

So, I have set up my images to display using:


Sprite::Sprite(SDL_Renderer* passed_renderer, string FilePath, int x, int y, int w, int h, CCollisionRect passed_collisionRect)
{
	CollisionRect = passed_collisionRect;

	renderer = passed_renderer;

	image = NULL;
	image = IMG_LoadTexture(renderer, FilePath.c_str());


	if (image == NULL){
		cout << "Couldn't load background" << FilePath.c_str();
	}

	rect.x = x;
	rect.y = y;
	rect.w = w;
	rect.h = h;

}

and then I draw them using:


player = new Sprite(setup->GetRenderer(), "images/player.png", 0, 500, 100, 100, CCollisionRect(0, 0, 100, 100));

and


	player->Draw();

Now, my question is, how would I get this and allow the player to jump?

Advertisement

If you are learning SDL i would recommend looking at lazy foo for reference for helping with some of the fundamentals. http://lazyfoo.net/SDL_tutorials/

Assuming you are just trying to do simple jumping something like this would work:


float myGravity = 0.2f;
float maxFallSpeed = -5.0f;
float myJumpForce = 5.0f;
float curJumpForce = 0.0f;
float deltaTime; (Time Between frames)

bool m_jumping = false;

if(press key){
   m_jumping = true;
   curJumpForce = myJumpForce;
}

if(m_jumping){
   player.y += curJumpForce * deltaTime;
   
   if(curJumpForce > maxFallSpeed){
      myJumpForce -= myGravity * deltaTime;
   }else{
      curJumpForce = maxFallSpeed;
   }

   if(Hit Ground){
      m_jumping = false;
   }
}

This is a quick mock up and will need to be properly implemented and numbers changed but it should work for a simple jump.

If you want a more technically accurate jump then you will need to look into acceleration and velocities.

getting a weird error http://gyazo.com/d150f509dd8fb4a1358725c203a43d10

Pasting the error message (along with the line it's complaining about) would be preferable to a screenshot of the error message.

Based on lordconstant's code, I would guess it's complaining about the player.y variable.

Your sprite code seems to indicate you don't have a y variable for your sprites, but you do have a rect.y variable. Try that.

That said, I would second the suggestion that you look at some tutorials, like the lazyfoo one that was already linked. It will guide you through a lot of these initials issues you're likely to face/question.

Hello to all my stalkers.

This topic is closed to new replies.

Advertisement