So i thought i had the idea of passing by reference down, but it seems i’m still struggling with it a bit.
Here’s my issue, i’ve been debugging my game for awhile, and i left the enemies section of my code untouched for ages. It’s a long story but i thought my projectiles were doing damage to the enemies, I changed the enemies health to being very high, so i thought they were doing the damage but because of the high health, not killing it. Only now have i realised that they are not doing any damage and that the code is wrong :/
So here is were i begin:
void Towers::Update(std::vector<Enemies>& enemies, SDLib& lib, Map cMap)
Here i’m passing the enemies by reference, into my update function. Which then i go onto see if there is any enemy within range of the tower;
for (int numOfEnemies = 0; numOfEnemies < lib.numberOfEnemies; numOfEnemies++)
{
float y = pow(enemies[numOfEnemies].position.y - position.y, 2);
float x = pow(enemies[numOfEnemies].position.x - position.x, 2);
if (sqrt(y + x) < range && enemies[numOfEnemies].alive)
{
cEnemy = enemies[numOfEnemies];
acquiredTarget = true;
break;
}
}
cEnemy (currentEnemy), then holds the enemy that’s within range. After this, i then create the projectile to fire, and here is were i think i’m messing up;
bullet = Projectile((float)position.x, (float)position.y - 8, 8, 8, 0, 0, damage, 1, speed, cEnemy);
And the function arguments for that are:
Projectile::Projectile(float x, float y, int w, int h, int sX, int sY, int dmg, int type, float mxSpeed, Enemies bulletTarget)
{
//....other values set.
target = bulletTarget;
}
(Target is the following)
Enemies target;
The idea here is that target should hold the reference to the initial enemy that i set it to via the function… But it isn’t working as i want.
I’m not too sure, but i’m guessing some form of pointer might be required here. It seems to be out of everything the concept i’m finding hardest to grasp *and have done for some time now.
Any help appreciated!
You are making a copy of the
Enemiesobject:cEnemy = enemies[numOfEnemies];Projectileconstructor, since it takes anEnemiesby value.target = bulletTarget;To fix all of these, you need to consider what code “owns” an
Enemiesobject and makes sure it lives long enough for all code that tries to use it. If there is such a place, all other places should use a reference or pointer. If not, maybe you can give the responsibility toshared_ptr<Enemies>.