c++sfmlgame-ai

Getting my enemy to move toward my player C++


I am trying to get my Enemy to move to my Player.

The thing I know :

The thing I need to do:

So what I thought I needed to do is to "normalize" the enemies' position according to the players position so I know where to go, and both have a position based on Vector2f.

And this is the code I have in the enemy:

void Enemy::Move()
{
    //cout << "Move" << endl;

    // Make movement
    Vector2f playerPosition = EntityManager::Instance().player.GetPosition();
    Vector2f thisPosition;
    thisPosition.x = xPos;
    thisPosition.y = yPos;
    //Vector2f direction = normalize(playerPosition - thisPosition);

    speed = 5;
    //EntityManager::Instance().enemy.enemyVisual.move(speed * direction);
}

Vector2f normalize(const Vector2f& source)
{
    float length = sqrt((source.x * source.x) + (source.y * source.y));
    if (length != 0)
        return Vector2f(source.x / length, source.y / length);
    else
        return source;
}

The error is :

'normalize': identifier not found

What am I doing wrong?


Solution

  • Your definition for normalize doesn't come until after you use it. Either move the definition before Enemy::Move, or put a function declaration at the top of your file after your includes:

    Vector2f normalize(const Vector2f& source);
    

    This is a small example of the same behavior.