I am trying to pass the member variable velocity in my enemies.cpp file and use it in the AI.cpp file to set the velocity to -300.
The code goes through to the AI.cpp file, however it doesn't set the velocity to -300 in my Enemies.cpp?
Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Enemies.cpp file
if (this->health > 75)
{
aI.SetAI(this->velocity);
}
AI.cpp file
void AI::SetAI(Vector2 velocity)
{
// First boss stage of AI
velocity.x = -300.0f;
}
Try changing line 10 to pass by reference instead: void AI::SetAI(Vector2& velocity)
As you have it, you are passing by value, which means that a copy is actually passed to the function and you are only modifying the copy. If you passed by reference (or pointer) instead, it means that the function instead receives the location in memory of the variable, and can therefore edit it directly. This is why it is also generally preferable to transfer large objects to functions by reference (or const reference) rather than by value, even if it isn't modified, because otherwise it can take longer to copy the data rather than reading from the data directly.