-1
\$\begingroup\$

I am having a problem on the console game I am making. How can I decrease the health of the character or enemy with loopings? My code goes like this by the way for example:

class RPG_Scene_Battle {
public:
  RPG_Scene_Battle(float ini_health) : health (ini_health){};
  float getHealth()
  {
      return health;

      }
  void setHealth(float rpg_val){ health = rpg_val;};

private:
  float health;
};

float conductDamage(RPG_Scene_Battle rpg_tr, float damage) {
  rpg_tr.setHealth(rpg_tr.getHealth() - damage);
  return rpg_tr.getHealth();
}

how can I do a do while loop to decrease the player and enemy's hp without returning the method? because returning the method conductDamage under the do loop would return the same value and not decrease constantly.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

The problem is that the conductDamage function uses a new copy of the RPG_Scene_Battle object on each invocation (the parameter is passed by value), you need to pass a reference to the object instead. Simplest way of doing this is to change the signature of the function to

float conductDamage(RPG_Scene_Battle &rpg_tr, float damage)
\$\endgroup\$
3
  • \$\begingroup\$ would it not copy the same function when we loop it? \$\endgroup\$
    – Angel
    Commented Aug 12, 2012 at 16:34
  • \$\begingroup\$ In the loop I assume you pass the same RPG_Scene_Battle object to conductDamage(), if you don't use pass-by-reference as described above the private object field health is only modified for the copy of the object - not the original object. This leads to the same value being returned on each invocation of conductDamage(). \$\endgroup\$
    – johlo
    Commented Aug 12, 2012 at 16:45
  • 1
    \$\begingroup\$ @Angel: Using a pass-by-reference speeds up the application tremendously too. Due to not copying all data into a new part of memory. So it is almost always the better choice for games that uses a loop. \$\endgroup\$
    – user18479
    Commented Aug 12, 2012 at 18:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .