SDL: Character collision with tiles.
Hello again.
I'm trying to learn SDL for some time now using LazyFoo's tutorials.
I'm currently trying to make a very simple platformer with a tile based level, but I can't quite get the character to behave right when he collides with the tiles.
This is the piece of code that seems to cause me all the trouble.
You may need a barf bag. :o
Code:
const int gravity = 10;
void sprite::events()
{
if( event.type == SDL_KEYDOWN )
{
switch( event.key.keysym.sym )
{
case SDLK_d:
moving = true;
vel += SPRITE_WIDTH / 4;
break;
case SDLK_a:
moving = true;
vel -= SPRITE_WIDTH / 4;
break;
default:
{
}
}
if( event.key.keysym.sym == SDLK_SPACE && jump == false )
{
jump = true;
jvel = -50;
}
}
if( event.type == SDL_KEYUP )
{
switch( event.key.keysym.sym )
{
case SDLK_d:
moving = false;
vel -= SPRITE_WIDTH / 4;
break;
case SDLK_a:
moving = false;
vel += SPRITE_WIDTH / 4;
break;
default:
{
}
}
}
}
void sprite::move( tile * tiles[] )
{
if( moving == true )
{
x += vel;
box.x = offs;
}
if( ( x < 0 ) || ( x + SPRITE_WIDTH > LEVEL_WIDTH ) || collision( box , tiles ) == true )
{
x -= vel;
box.x = x;
}
y += jvel;
jvel += gravity;
box.y = y;
if( jvel >= gravity * 5 )
{
jvel = gravity * 5;
}
if( y > LEVEL_HEIGHT )
{
y = 0;
x = 0;
jvel = 0;
}
if( collision( box , tiles ) == true )
{
jump = false;
y -= jvel;
box.y = y;
jvel = 0;
}
}
When the character stands on a tile, he continuously jumps 10 pixels up and down.
From what I understand, this is caused by gravity. When the character collides with the tiles, y (the character position) gets reduced by jvel, and jvel becomes 0. But then, gravity makes jvel 10 again, and y gets reduced by it to start all over.
If I do not turn jvel to 0, the character will stank OK on the ground, but if he jumps on a platform he will be standing jvel pixels above it.
I'm not sure what to do here, so some help will be appreciated.
Also, when the character bumps his head on the bottom of a platform, he will start ascending until he gets on top of it. This is probably related to my main problem. I want the vertical collision to behave quite like the horizontal, but I don't know how.
Another minor problem is that when the character falls on a hole and re-enters the level, he falls through the tiles instead of landing of them. But if I press left or right while he's falling, he lands OK. I'm not sure what causes this, though.
Thank you in advance. :)
SDL libraries instalation problem.
Hello, I'have download the SDL libraries on official website and I try to instal it. Librarie are decompressed and I put SDL.dll with my program in C. She is called in my program with the command "#include <SDL/SDL.h>. I try to compile a simple program (open a window), the software indicates an error "SDL_Init has not found ..." and for all SDL functions.
thank you for the gait to indicate that the software finds the good way.