虚幻4实现自己移动的AI人物
程序员文章站
2022-06-04 18:38:08
...
自己用作记录,如果想学习的直接去看这篇文章吧。
设置好导航体积覆盖整个关卡,然后创建一个aicontroller类
用到如下几个api。
- GetAllActorsOfClass查找关卡中所有的目标点
- MoveToActor移动到某一个目标点
- OnMoveCompleted移动完成会自动调用
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyAIController.h"
#include "AIController.h"
void AMyAIController::BeginPlay()
{
Super::BeginPlay();
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ATargetPoint::StaticClass(), Waypoints);
GoToRandomWaypoint();
}
ATargetPoint* AMyAIController::GetRandomWaypoint()
{
int32 index = FMath::RandRange(0, Waypoints.Num() - 1);
return Cast<ATargetPoint>(Waypoints[index]);
}
void AMyAIController::GoToRandomWaypoint()
{
MoveToActor(GetRandomWaypoint());
}
void AMyAIController::OnMoveCompleted(FAIRequestID RequestID, const FPathFollowingResult& Result)
{
Super::OnMoveCompleted(RequestID, Result);
GoToRandomWaypoint();
}
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "AIController.h"
#include "Engine/TargetPoint.h"
#include "Kismet/GameplayStatics.h"
#include "MyAIController.generated.h"
/**
*
*/
UCLASS()
class TAG_API AMyAIController : public AAIController
{
GENERATED_BODY()
public:
void BeginPlay() override;
void OnMoveCompleted(FAIRequestID RequestID, const FPathFollowingResult& Result) override;
private:
UPROPERTY()
TArray<AActor*> Waypoints;
UFUNCTION()
ATargetPoint* GetRandomWaypoint();
UFUNCTION()
void GoToRandomWaypoint();
};
8.28更新
#include "MyAIController.h"
#include "AIController.h"
AMyAIController::AMyAIController()
{
PrimaryActorTick.bCanEverTick = true;
}
void AMyAIController::BeginPlay()
{
Super::BeginPlay();
}
FVector AMyAIController::GetRandomWaypoint()
{
//这里两种写法,采用的一种是为了再多人游戏中也能进行拓展
FVector myPlayer1 = UGameplayStatics::GetPlayerController(GetWorld(), 0)->GetPawn()->GetActorLocation();
//FVector myPlayer = GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorLocation();
return myPlayer1;
}
void AMyAIController::GoToRandomWaypoint()
{
FVector PlayerLocation = GetRandomWaypoint();
FVector EnemyLocation = GetCharacter()->GetActorLocation();
//计算ai需要面朝的方向
FVector EnemyDirect = PlayerLocation - EnemyLocation;
//因为发现人物不会自己转向了,就加了这一句。
this->GetCharacter()->FaceRotation(EnemyDirect.Rotation(), 0.2);
MoveToLocation(PlayerLocation, 5);
}
void AMyAIController::Tick(float DeltaTime)
{
GoToRandomWaypoint();
}
修改了一下代码实现了一直跟随玩家。再tick中调用是为了即时更新GoToRandomWaypoint使用的玩家位置
推荐阅读