[sdl] Sprite Locations When Using A Camera


motorollin

Member
Joined
Jul 31, 2007
Messages
163
I'm writing my first ever game for the GP2X using the official SDK. I used the Lazy Foo scrolling tutorial to get my sprite moving around a scrolling background. I'm now trying to add an enemy to the game, but when I specify the x and y co-ordinates for the sprite, these co-ordinates are relative to the camera, not the background. So the following code places the enemy in the top left of the camera, not in the top left of the playfield.

CODE
Enemy::Enemy()
{
x=0;
y=0;
xVel=0;
yVel=0;
}


As the player moves around and the screen scrolls, the enemy stays in the top left corner instead of scrolling off the screen. So my question is this: how can I specify co-ordinates for the enemy relative to the whole game instead of relative to the camera?

TIA
 
Use the x and y as normal offsets of your level and only when you draw the sprite make sure it is relative to the camera.

So say if you want an enemy at (100,150) and your camera was at (50,100)
then you would draw the sprite at on the screen at -
(100-50, 150 - 100) = (50,50).

Make sure you check if the unit collides with the camera before you draw it.
So if your camera does not collide with the enemy ie when the enemy is at (0,50) and the camera is at say (400,50) dont draw it on the screen.

I hope that helps. :)
 
Hi Uprising, thanks for your quick response! I think I understand what you mean. Modifying my original code looks like this:

CODE
Enemy::Enemy()
{
x=100-camera.x;
y=50-camera.y;
xVel=0;
yVel=0;
}


Is that what you meant?
 
Not quite, only take away the camera.x and camera.y when you draw it.:)

Enemy::Enemy()
{
x=100;
y=50;
xVel=0;
yVel=0;
}

apply_surface(enemy.x - camera.x,enemy.y - camera.y, enemySprite, screen );
 
Ahhh, got it:

CODE
Enemy:: Enemy()
{
x=100;
y=100;
xVel=0;
yVel=0;
}

void Enemy::show()
{
frame++;

//Loop the animation
if( frame >= 10 )
{
frame = 0;
}

//Show the Enemy
apply_surface( x - camera.x, y - camera.y, Enemy, screen, &enemyClips[ frame ] );
}


My mistake was putting the offset minus camera location in the Enemy constructor, not in its show() function. Thanks a lot for your help!
 
Was dealing with the same problems with my next game Blockland, but got everything worked out fine.

What always helps is making a sketch to your problem to see how to calculate stuff like that.
 
Back
Top