Hello Guys, i'm started with sdl and i have a little problem. The problem is that when you move the sprite drawing she leaves the "sprite" through which it passes. I am using the following code.
main.h
#ifndef _MAIN_H_
#define _MAIN_H_
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#define SCREEN_BPP 32
SDL_Surface *screen = NULL;
SDL_Surface *image = NULL;
void sdl_init(void);
void sdl_finish(void);
void draw_image(int x, int y, int width, int height, SDL_Surface *screenSurface, SDL_Surface *imageSurface);
#endif
main.c
#include "main.h"
/* Init */
void sdl_init(void)
{
if(SDL_Init(SDL_INIT_EVERYTHING))
{
fprintf(stderr, "Error in initialization the systems: %s\n", SDL_GetError());
exit(-1);
}
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
if(!screen)
{
fprintf(stderr, "Error to create the window: %s\n", SDL_GetError());
exit(-1);
}
SDL_WM_SetCaption("001", NULL);
return;
}
/* Finalization */
void sdl_finish(void)
{
SDL_FreeSurface(image);
SDL_Quit();
return;
}
/* Desenha as sprites */
void draw_image(int x, int y, int width, int height, SDL_Surface *screenSurface, SDL_Surface *imageSurface)
{
SDL_Rect dest, src;
src.x = 0;
src.y = 0;
src.w = width;
src.h = height;
dest.x = x;
dest.y = y;
dest.w = width;
dest.h = height;
SDL_BlitSurface(imageSurface, &src, screenSurface, &dest);
return;
}
/* Main Function */
int main(int argc, char *argv[])
{
int gameQuit = 1;
int imgX = 0,
imgY = 0;
SDL_Event event;
int key[323] = {0};
sdl_init();
image = SDL_LoadBMP("sPlayer.bmp");
if(!image)
{
fprintf(stderr, "Error to load image: %s\n", SDL_GetError());
exit(-1);
}
while(gameQuit)
{
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
gameQuit = 0;
if(event.type == SDL_KEYDOWN)
{
key[event.key.keysym.sym] = 1;
}
if(event.type == SDL_KEYUP)
{
key[event.key.keysym.sym] = 0;
}
}
/* Keys */
if(key[SDLK_DOWN] && ((imgY + image->h) < SCREEN_HEIGHT))
imgY += 1;
if(key[SDLK_UP] && (imgY > 0))
imgY -= 1;
if(key[SDLK_RIGHT] && ((imgX + image->w) < SCREEN_WIDTH))
imgX += 1;
if(key[SDLK_LEFT] && (imgX > 0))
imgX -= 1;
if(key[SDLK_ESCAPE])
gameQuit = 0;
/* Draw */
draw_image(imgX, imgY, image->w, image->h, screen, image);
/* Update */
SDL_Flip(screen);
}
sdl_finish();
return 0;
}
But if i add the following piece of code in down of SDL_Flip.
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
And here I have another problem because the sdl will not repeat over the sprite, but that will not cause error on the screen will be redrawn simply making the sprite is below the anterior surface of the screen causing errors later, because of the amount of images that would be on the screen. Or am I wrong.
I was wondering how do I update the image and not out showing a lot of repeated images. And if sdl_fillrect do this and I am wrong as to hide the images under the surface.