My player flies around the screen in any direction he wants, and the camera follows him. There are stars in the background. I can't figure out how to randomly generate the stars. I made a star class. There are a few different types of stars, and some have different depths than others, hence they move slower as the player moves around. I can create a stars around the player when the game starts, and when they get 100 pixels off the screen they are destroyed, but I can't figure out a good way to create new stars.
Here is my code: Star Class:
#pragma once
struct Star
{
int xposition, yposition;
int type;
int velocity;
bool alive;
Star()
{
xposition = yposition = 0;
type = 0;
velocity = 0;
alive = false;
}
void create( int p_xposition, int p_yposition, int p_velocity, int p_type )
{
xposition = p_xposition;
yposition = p_yposition;
velocity = p_velocity;
type = p_type;
alive = true;
}
void destroy()
{
alive = false;
}
};
Background Class:
#include "background.h"
void Background::init( Engine* p_engine, SDL_Rect* p_camera )
{
engine = p_engine;
camera = p_camera;
delta_time = SDL_GetTicks();
for ( int s = 0; s < 100; s++ )
{
stars[s] = new Star;
}
image[0] = engine->load_image( "star 1.png" );
image[1] = engine->load_image( "star 2.png" );
image[2] = engine->load_image( "star 3.png" );
image[3] = engine->load_image( "star 4.png" );
for ( int s = 0; s < 30; s++ )
{
for ( int s2 = 0; s2 < 100; s2++ )
{
if ( stars[s2]->alive == false )
{
stars[s2]->create( rand() % engine->screen_width, rand() % engine->screen_height, rand() % 30, rand() % 4 );
break;
}
}
}
}
void Background::cleanup()
{
for ( int s = 0; s < 100; s++ )
{
delete stars[s];
}
for ( int i = 0; i < 4; i++ )
{
SDL_FreeSurface( image[i] );
}
}
void Background::logic()
{
delta_time = SDL_GetTicks() - delta_time;
//destroy stars
for ( int s = 0; s < 100; s++ )
{
if ( stars[s]->alive == true )
{
if ( stars[s]->xposition < camera->x - 100 || stars[s]->xposition > camera->x + camera->w + 100 )
{
stars[s]->destroy();
}
}
if ( stars[s]->alive == true )
{
if ( stars[s]->yposition < camera->y - 100 || stars[s]->yposition > camera->y + camera->h + 100 )
{
stars[s]->destroy();
}
}
}
//create stars
if ()
{
}
delta_time = SDL_GetTicks();
}
void Background::render()
{
for ( int s = 0; s < 100; s++ )
{
if ( stars[s]->alive == true )
{
engine->apply_surface( image[stars[s]->type], engine->buffer, stars[s]->xposition - camera->x, stars[s]->yposition - camera->y );
}
}
}