Download

MoveToLocation C++

hello,
I am new to c++ and UE4 and i have a question.
I made an AI character and controller and I am trying to move him to a random Fvector In a certain radius.
my question is how do i set up the functions in the c++ because the MoveToLocation takes a const fvector&.
i know its kind of a novice question but like i said i am new to the engine and language.

header:


    FVector& GetRandomPos() const;

cpp:


FVector& AAI_Zombie_Controller::GetRandomPos() const
{
}

i want to call the function from here:


void AAI_Zombie_Controller::Tick(float DeltaSeconds)
{
    Super::Tick(DeltaSeconds);
    if (DistanceToPlayer > AISightRadius)
    {
         bIsPlayerDetected = false;
    }
    if (!bIsPlayerDetected)
    {
        if (bGotToPos)
        {
            MoveToLocation(&AAI_Zombie_Controller::GetRandomPos);
            bGotToPos = false;
        }
    }
    else
    {
        ALostCharacter* Player = Cast<ALostCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
        MoveToActor(Player,5.0f);
    }
}



FVector GetRandomPos() const;




FVector AAI_Zombie_Controller::GetRandomPos() const
{
//  My random vector implementation goes here
 FVector MyRandomVector;

 return MyRandomVector;
}




void AAI_Zombie_Controller::Tick(float DeltaSeconds)
{
    Super::Tick(DeltaSeconds);
    if (DistanceToPlayer > AISightRadius)
    {
         bIsPlayerDetected = false;
    }
    if (!bIsPlayerDetected)
    {
        if (bGotToPos)
        {
            FVector Destination = GetRandomPos();
            MoveToLocation(Destination);
            bGotToPos = false;
        }
    }
    else
    {
        ALostCharacter* Player = Cast<ALostCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
        MoveToActor(Player,5.0f);
    }
}


It should look something like that.
With my luck this will probably have about 10 errors and 200 warnings. But I’m sure you will figure it out. :slight_smile:

It worked just fine thank you :slight_smile:
Didn’t get why the function didn’t need to return a fvector&.
Is it because its already a reference

The following does not call the function but rather gets the function’s address in memory. Your trying to pass the functions memory address as a parameter to MoveLocation instead of an FVector.



// Get address of GetRandomPos function, this is not a function call
MoveToLocation(&AAI_Zombie_Controller::GetRandomPos);


To use a reference with GetRandomPos you’d have to change the code I wrote above as follows. There is no return in this case.




// In header
GetRandomPos(FVector& MyRandomVector) const;


// In cpp
AAI_Zombie_Controller::GetRandomPos(FVector& MyRandomVector) const
{
//  My random vector implementation goes here
MyRandomVector = UpdatedFVectorValue;
}



// Update call as follows




FVector Destination;
GetRandomPos(Destination);
MoveToLocation(Destination);