In a simple SDL 'game', the player picks up 5 coins to win. The coin is 'picked up' when the player touches it and a new coin is spawned in another random location.
However, in the code, when the player picks up the item, the item doesn't disappear; it's position is simply moved. (I found it much easier to do it this way)
1 2 3 4 5 6 7 8 9
|
if(player.x + player.width > item.x
&& player.x < item.x + item.width
&& player.y + player.height > item.y
&& player.y < item.y + item.height)
{
score++;
item.x = random(0, SCREEN_WIDTH - item.width);
item.y = random(0, SCREEN_HEIGHT - item.height);
}
|
[I should add that
random() is my own function that simply uses
rand to generate a number in a given range]
Q1: Is this the way I should do it? I feel I would get more practice if instead I deleted the object when it is 'picked up' and created a new one. (The idea that the object just 'moves' also feels wrong to me.) If this is a better option, how would I do this?
___________________________________________________________________________
In another simple game, enemies can spawn and be killed. The way I am doing this is by using a vector of the enemy objects, and adding a new object when a new enemy spawns. (At the moment, this is not implemented, but I have tested using objects in this way).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
class Zombie
{
public:
Zombie(int a=100);
int health;
};
Zombie::Zombie(int a)
{
health = a;
cout << "zombie spawned with " << health << " health\n";
}
class Horde
{
public:
Horde(int spaces = 1);
void Add(const Zombie& zombie);
void Display();
void Remove(const Zombie& zombie);
vector<Zombie> zombies;
};
Horde::Horde(int spaces)
{
zombies.reserve(spaces);
}
void Horde::Add(const Zombie& zombie)
{
zombies.push_back(zombie);
}
void Horde::Display()
{
for(vector<Zombie>::const_iterator iter = zombies.begin();
iter != zombies.end();
++iter)
{
cout << iter->health << " health\n";
}
}
|
[This code shows how I am using a vector of objects - in this case, zombies - and how I am iterating through them. (It also acts as a way of showing how terrible I am at using vectors)]
Q2: How would I remove a specific enemy from the vector? I know
erase is very inefficient, but it seems most suitable in this case. And how do I refer to this specific object in the vector? I will know which enemy needs to be removed, because I will iterate through the vector and check for collisions with each tick. However, I don't know how I use this erase an object from the vector.