// A function to move the sprite
void move_sprite(t_sprite *sprite, int x, int y)
{
// If the sprite is within the width boundaries, move the sprite
if( (sprite->rect.w < 800) && (sprite->rect.x > -1) )
{
sprite->rect.x = sprite->rect.x + x;
sprite->rect.w = sprite->rect.w + x;
}
// If the sprite is within the height boundaries, move the sprite
if( (sprite->rect.h < 600) && (sprite->rect.y > -1) )
{
sprite->rect.y = sprite->rect.y + y;
sprite->rect.h = sprite->rect.h + y;
}
}
keeping the player within the screen boundaries
I am making an SDL 2D game named WWI Ace , and I want to make it so that the player''s movement is constrained to a certain portion of the screen. This sounds really simple to implement, but I am doing something wrong. this is the source for the function that moves sprites around the screen:
I think it is pretty self-explanatory. I want the sprite to be moved within the 800x600 screen. I cannot figure out what is wrong with this. Thank you for your consideration.
The sprite will not stop at the end of the screen. It just moves past. It won''t move past the top and left part, but the bottom and right part it just moves freely around in. I want to make it so that it is within that boundary, but it has no problem with going out of the boundary.
if( (sprite->rect.w < 800) && (sprite->rect.x > -1) )
You''re comparing w to 800 instead of x.
Well, it depends. Is the w and h supposed to be the right and bottom edges, or is it the width and height of the image? But if I do use x it does work for some reason.
If it''s supposed to be the right and bottom edge, someone should be shot for calling it "w" and "h", which any sane person would take to represent width and height.
If that''s the case, you probably shouldn''t be incrementing them by x and y when you move your sprite around...
If that''s the case, you probably shouldn''t be incrementing them by x and y when you move your sprite around...
It works now. Thank you everyone that posted. The only problem is that whenever the plane hits the bottom and right walls it vibrates back and forth if you keep holding the key down. On the left and top walls, the plane moves through the wall about 10 pixels or so, and then when you release the key it goes back. Does anyone know what is going on here? Any help would be much appreciated. Thanks.
I haven''t proceeded to make a game with SDL yet, but used the following code to keep my image on screen and it does not jump back and forth when you hold the keys down.
// dest is a SDL_Rect that is updated before this code is tested// SCR_WIDTH and SCR_HEIGHT are const ints that denote the screen sizeif ((image->w + dest.x) >=SCR_WIDTH) dest.x = SCR_WIDTH - image->w;if ((image->h + dest.y) >=SCR_HEIGHT) dest.y = SCR_LENGTH - image->h;// The blitting code is after this test
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement