void ASpawnEnemy::SpawnRandomEnemy() { TArray<FString> Parsed; TArray<FString> HowMuch; TArray<FString> TypeEnemy; const TCHAR* Delims[] = { TEXT(":"), TEXT(";") }; float RandomNumber = (float)rand() / (float)RAND_MAX; int SetNumber = RandomNumber * (Enemies.Num()); Enemies[SetNumber].ParseIntoArray(&Parsed, Delims, 2); int SizeOfArrayParsed = Parsed.Num() - 1; for (int x = 0; x <= SizeOfArrayParsed; x = x + 2) { HowMuch.Add(Parsed[x]); } for (int x = 1; x <= SizeOfArrayParsed; x = x + 2) { TypeEnemy.Add(Parsed[x]); } for (auto Itr(HowMuch.CreateIterator()); Itr; Itr++) { APawn* NewPawn = NULL; FVector BoxOnWorld = GetActorLocation(); FRotator RotatorBoxOnWorld = GetActorRotation(); FBox BoxInfo = GetComponentsBoundingBox(); FVector BoxSize = BoxInfo.GetSize(); if (TypeEnemy[Itr.GetIndex()] == "PegEnemyLight") { EnemyClass = PegLightEnemyClass; } else if (TypeEnemy[Itr.GetIndex()] == "PegDarkEnemy") { EnemyClass = PegDarkEnemyClass; } else if (TypeEnemy[Itr.GetIndex()] == "GarbageEnemy") { EnemyClass = GarbageEnemyClass; } else if (TypeEnemy[Itr.GetIndex()] == "MeleeBookEnemy") { EnemyClass = MeleeBookEnemyClass; } else if (TypeEnemy[Itr.GetIndex()] == "RangeBookEnemy") { EnemyClass = RangeBookEnemyClass; } else if (TypeEnemy[Itr.GetIndex()] == "PianoChargeEnemy") { EnemyClass = PianoEnemyClass; } else if (TypeEnemy[Itr.GetIndex()] == "BarrelChargeEnemy") { EnemyClass = BarrelEnemyClass; } else if (TypeEnemy[Itr.GetIndex()] == "FridgeChargeEnemy") { EnemyClass = FridgeEnemyClass; } if (GetWorld()) { int32 MyShinyNewInt = FCString::Atoi(*HowMuch[Itr.GetIndex()]); for (int x = 1; x <= MyShinyNewInt; x++) { float random = (float)rand() / (float)RAND_MAX; float randomy = (float)rand() / (float)RAND_MAX; int xValue = 1 + random * ((3) - (1)); int yValue = 1 + randomy * ((3) - (1)); float z, y; if (xValue == 1) z = random * (0 + (BoxSize[0] / 2)); else z = random * (0 - (BoxSize[0] / 2)); if (yValue == 1) y = random * (0 + (BoxSize[1] / 2)); else y = random * (0 - (BoxSize[1] / 2)); BoxOnWorld[0] += z; BoxOnWorld[1] += y; if (ShouldSpawnEnemies) { if (BoxInfo.IsInside(BoxOnWorld)) { NewPawn = GetWorld()->SpawnActor<AAI_BasicEnemy>(EnemyClass, BoxOnWorld, RotatorBoxOnWorld); FVector BoxOnWorld = GetActorLocation(); if (NewPawn != NULL) { if (NewPawn->Controller == NULL) { NewPawn->SpawnDefaultController(); } if (BehaviorTree != NULL) { AAIController* AIController = Cast<AAIController>(NewPawn->Controller); if (AIController != NULL) { AIController->RunBehaviorTree(BehaviorTree); } } } //AI Direct laten aanvallen wanneer die spawnt! AAI_BasicController* Controller = (AAI_BasicController*)NewPawn->GetController(); Controller->FoundPlayer(); Controller->AISetAttackState(); } } } } } EnemyClass = NULL; APawn* NewPawn = NULL; }
EBTNodeResult::Type UBTTask_MoveDirectlyToward::AbortTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { FBTMoveDirectlyTowardMemory* MyMemory = reinterpret_cast<FBTMoveDirectlyTowardMemory*>(NodeMemory); AAIController* MyController = OwnerComp.GetAIOwner(); if (MyController && MyController->GetPathFollowingComponent()) { MyController->GetPathFollowingComponent()->AbortMove(TEXT("BehaviorTree abort"), MyMemory->MoveRequestID); } return Super::AbortTask(OwnerComp, NodeMemory); }
EBTNodeResult::Type UPBTask_Attack::ExecuteTask(UBehaviorTreeComponent* OwnerComp, uint8* NodeMemory) { AAIController * Controller = OwnerComp ? Cast<AAIController>(OwnerComp->GetOwner()) : nullptr; APBEnemy * Enemy = Controller ? Cast<APBEnemy>(Controller->GetCharacter()) : nullptr; if (Enemy) { Enemy->Attack(); } return EBTNodeResult::Succeeded; }
//======================================================================== void C_DudeMoveTo::Start() { AAIController* controller = CastChecked<AAIController>(m_Dude.GetController()); auto ret = controller->MoveToLocation(target, -1.f, true, true, false, true, 0, false); //do not allow partial paths! if (ret == EPathFollowingRequestResult::Failed) { m_Dude.ClearActionQueue(); cbHandle.Reset(); } else { cbHandle = controller->GetPathFollowingComponent()->OnMoveFinished.AddRaw(this, &C_DudeMoveTo::OnMoveCompleted); } }
UAIAsyncTaskBlueprintProxy* UAIBlueprintHelperLibrary::CreateMoveToProxyObject(UObject* WorldContextObject, APawn* Pawn, FVector Destination, AActor* TargetActor, float AcceptanceRadius, bool bStopOnOverlap) { check(WorldContextObject); if (!Pawn) { return NULL; } UAIAsyncTaskBlueprintProxy* MyObj = NULL; AAIController* AIController = Cast<AAIController>(Pawn->GetController()); if (AIController) { UWorld* World = GEngine->GetWorldFromContextObject( WorldContextObject ); MyObj = NewObject<UAIAsyncTaskBlueprintProxy>(World); FAIMoveRequest MoveReq; MoveReq.SetUsePathfinding(true); MoveReq.SetAcceptanceRadius(AcceptanceRadius); MoveReq.SetStopOnOverlap(bStopOnOverlap); if (TargetActor) { MoveReq.SetGoalActor(TargetActor); } else { MoveReq.SetGoalLocation(Destination); } FPathFindingQuery Query; const bool bValidQuery = AIController->PreparePathfinding(MoveReq, Query); if (bValidQuery) { const FAIRequestID RequestID = AIController->RequestPathAndMove(MoveReq, Query); if (RequestID.IsValid()) { MyObj->AIController = AIController; MyObj->AIController->ReceiveMoveCompleted.AddDynamic(MyObj, &UAIAsyncTaskBlueprintProxy::OnMoveCompleted); MyObj->MoveRequestId = RequestID; } else { World->GetTimerManager().SetTimer(MyObj->TimerHandle_OnNoPath, MyObj, &UAIAsyncTaskBlueprintProxy::OnNoPath, 0.1f, false); } } } return MyObj; }
EBTNodeResult::Type UBTTask_MoveDirectlyToward::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { const UBlackboardComponent* MyBlackboard = OwnerComp.GetBlackboardComponent(); FBTMoveDirectlyTowardMemory* MyMemory = reinterpret_cast<FBTMoveDirectlyTowardMemory*>(NodeMemory); AAIController* MyController = OwnerComp.GetAIOwner(); EBTNodeResult::Type NodeResult = EBTNodeResult::Failed; if (MyController && MyBlackboard) { EPathFollowingRequestResult::Type RequestResult = EPathFollowingRequestResult::Failed; if (BlackboardKey.SelectedKeyType == UBlackboardKeyType_Object::StaticClass()) { UObject* KeyValue = MyBlackboard->GetValue<UBlackboardKeyType_Object>(BlackboardKey.GetSelectedKeyID()); AActor* TargetActor = Cast<AActor>(KeyValue); if (TargetActor) { RequestResult = bDisablePathUpdateOnGoalLocationChange ? MyController->MoveToLocation(TargetActor->GetActorLocation(), AcceptableRadius, bStopOnOverlap, /*bUsePathfinding=*/false, /*bProjectDestinationToNavigation=*/bProjectVectorGoalToNavigation, bAllowStrafe) : MyController->MoveToActor(TargetActor, AcceptableRadius, bStopOnOverlap, /*bUsePathfinding=*/false, bAllowStrafe); } } else if (BlackboardKey.SelectedKeyType == UBlackboardKeyType_Vector::StaticClass()) { const FVector TargetLocation = MyBlackboard->GetValue<UBlackboardKeyType_Vector>(BlackboardKey.GetSelectedKeyID()); RequestResult = MyController->MoveToLocation(TargetLocation, AcceptableRadius, bStopOnOverlap, /*bUsePathfinding=*/false, /*bProjectDestinationToNavigation=*/bProjectVectorGoalToNavigation, bAllowStrafe); } if (RequestResult == EPathFollowingRequestResult::RequestSuccessful) { const FAIRequestID RequestID = MyController->GetCurrentMoveRequestID(); MyMemory->MoveRequestID = RequestID; WaitForMessage(OwnerComp, UBrainComponent::AIMessage_MoveFinished, RequestID); NodeResult = EBTNodeResult::InProgress; } else if (RequestResult == EPathFollowingRequestResult::AlreadyAtGoal) { NodeResult = EBTNodeResult::Succeeded; } } return NodeResult; }
void UPerceptionGameplayDebuggerObject::CollectDataToReplicate(APlayerController* MyPC, AActor *SelectedActor) { Super::CollectDataToReplicate(MyPC, SelectedActor); #if ENABLED_GAMEPLAY_DEBUGGER if (GetWorld()->TimeSeconds - LastDataCaptureTime < 2) { return; } APawn* MyPawn = Cast<APawn>(SelectedActor); if (MyPawn) { AAIController* BTAI = Cast<AAIController>(MyPawn->GetController()); if (BTAI) { UAIPerceptionComponent* PerceptionComponent = BTAI->GetAIPerceptionComponent(); if (PerceptionComponent == nullptr) { PerceptionComponent = MyPawn->FindComponentByClass<UAIPerceptionComponent>(); } if (PerceptionComponent) { TArray<FString> PerceptionTexts; GenericShapeElements.Reset(); PerceptionComponent->GrabGameplayDebuggerData(PerceptionTexts, GenericShapeElements); DistanceFromPlayer = DistanceFromSensor = -1; if (MyPC && MyPC->GetPawn()) { DistanceFromPlayer = (MyPawn->GetActorLocation() - MyPC->GetPawn()->GetActorLocation()).Size(); DistanceFromSensor = SensingComponentLocation != FVector::ZeroVector ? (SensingComponentLocation - MyPC->GetPawn()->GetActorLocation()).Size() : -1; } } UAIPerceptionSystem* PerceptionSys = UAIPerceptionSystem::GetCurrent(MyPawn->GetWorld()); if (PerceptionSys) { PerceptionLegend = PerceptionSys->GetPerceptionDebugLegend(); } } } #endif }
void UGameplayDebuggingComponent::CollectBehaviorTreeData() { #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) if (!ShouldReplicateData(EAIDebugDrawDataView::BehaviorTree)) { return; } BrainComponentName = TEXT(""); BrainComponentString = TEXT(""); APawn* MyPawn = Cast<APawn>(GetSelectedActor()); AAIController* MyController = Cast<AAIController>(MyPawn->Controller); if (MyController != NULL && MyController->BrainComponent != NULL && MyController->IsPendingKillPending() == false) { BrainComponentName = MyController->BrainComponent != NULL ? MyController->BrainComponent->GetName() : TEXT(""); BrainComponentString = MyController->BrainComponent != NULL ? MyController->BrainComponent->GetDebugInfoString() : TEXT(""); BlackboardString = MyController->BrainComponent->GetBlackboardComponent() ? MyController->BrainComponent->GetBlackboardComponent()->GetDebugInfoString(EBlackboardDescription::KeyWithValue) : TEXT(""); if (World && World->GetNetMode() != NM_Standalone) { TArray<uint8> UncompressedBuffer; FMemoryWriter ArWriter(UncompressedBuffer); ArWriter << BlackboardString; const int32 HeaderSize = sizeof(int32); BlackboardRepData.Init(0, HeaderSize + FMath::TruncToInt(1.1f * UncompressedBuffer.Num())); const int32 UncompressedSize = UncompressedBuffer.Num(); int32 CompressedSize = BlackboardRepData.Num() - HeaderSize; uint8* DestBuffer = BlackboardRepData.GetData(); FMemory::Memcpy(DestBuffer, &UncompressedSize, HeaderSize); DestBuffer += HeaderSize; FCompression::CompressMemory((ECompressionFlags)(COMPRESS_ZLIB | COMPRESS_BiasMemory), (void*)DestBuffer, CompressedSize, (void*)UncompressedBuffer.GetData(), UncompressedSize); BlackboardRepData.SetNum(CompressedSize + HeaderSize, false); } } #endif //!(UE_BUILD_SHIPPING || UE_BUILD_TEST) }
void AEventExampleProjectPlayerController::SetNewMoveDestination(const FVector DestLocation) { if (ControlledActors.Num() > 0) { UNavigationSystem* const NavSys = GetWorld()->GetNavigationSystem(); for (auto ctr : ControlledActors) { if (!ctr.IsValid()) continue; AAIController * controlled = ctr.Get(); APawn *pPawn = controlled->GetPawn(); if (pPawn) { float const Distance = FVector::Dist(DestLocation, pPawn->GetActorLocation()); // We need to issue move command only if far enough in order for walk animation to play correctly if (NavSys && (Distance > 120.0f)) { NavSys->SimpleMoveToLocation(controlled, DestLocation); } } } } }
void UAIBlueprintHelperLibrary::UnlockAIResourcesWithAnimation(UAnimInstance* AnimInstance, bool bUnlockMovement, bool UnlockAILogic) { if (AnimInstance == NULL) { return; } APawn* PawnOwner = AnimInstance->TryGetPawnOwner(); if (PawnOwner) { AAIController* OwningAI = Cast<AAIController>(PawnOwner->Controller); if (OwningAI) { if (bUnlockMovement && OwningAI->GetPathFollowingComponent()) { OwningAI->GetPathFollowingComponent()->ClearResourceLock(EAIRequestPriority::HardScript); } if (UnlockAILogic && OwningAI->BrainComponent) { OwningAI->BrainComponent->ClearResourceLock(EAIRequestPriority::HardScript); } } } }
void AChangeable::Change() { FActorSpawnParameters SpawnParameters = FActorSpawnParameters(); SpawnParameters.bNoCollisionFail = true; APawn* Pawn = GetWorld()->SpawnActor<APawn>(TargetClass, GetActorLocation(), GetActorRotation(), SpawnParameters); if (Pawn) { if (Pawn->Controller) { Pawn->SpawnDefaultController(); } if (BehaviorTree != NULL) { AAIController* AIController = Cast<AAIController>(Pawn->Controller); if (AIController != NULL) { AIController->RunBehaviorTree(BehaviorTree); } } } Destroy(); }
APawn* UKismetAIHelperLibrary::SpawnAI(class UObject* WorldContextObject, UBlueprint* Pawn, class UBehaviorTree* BehaviorTree, FVector Location, FRotator Rotation, bool bNoCollisionFail) { APawn* NewPawn = NULL; UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject); if (World && Pawn && BehaviorTree) { FActorSpawnParameters ActorSpawnParams; ActorSpawnParams.bNoCollisionFail = bNoCollisionFail; NewPawn = World->SpawnActor<APawn>(Pawn->GeneratedClass, Location, Rotation, ActorSpawnParams); ActorSpawnParams.bNoCollisionFail = true; if (NewPawn != NULL) { if (NewPawn->Controller == NULL) { AAIController* NewController = World->SpawnActor<AAIController>(AAIController::StaticClass(), ActorSpawnParams); if (NewController) { NewController->Possess(NewPawn); } } AAIController* AIController = Cast<AAIController>(NewPawn->Controller); if (AIController != NULL) { AIController->RunBehaviorTree(BehaviorTree); } } } return NewPawn; }
EBTNodeResult::Type UBTTask_MoveDirectlyToward::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { const UBlackboardComponent* MyBlackboard = OwnerComp.GetBlackboardComponent(); FBTMoveDirectlyTowardMemory* MyMemory = reinterpret_cast<FBTMoveDirectlyTowardMemory*>(NodeMemory); AAIController* MyController = OwnerComp.GetAIOwner(); EBTNodeResult::Type NodeResult = EBTNodeResult::Failed; if (MyController && MyBlackboard) { if (GET_AI_CONFIG_VAR(bEnableBTAITasks)) { UAITask_MoveTo* AIMoveTask = NewBTAITask<UAITask_MoveTo>(OwnerComp); if (AIMoveTask != nullptr) { bool bSetUp = false; if (BlackboardKey.SelectedKeyType == UBlackboardKeyType_Object::StaticClass()) { UObject* KeyValue = MyBlackboard->GetValue<UBlackboardKeyType_Object>(BlackboardKey.GetSelectedKeyID()); AActor* TargetActor = Cast<AActor>(KeyValue); if (TargetActor) { AIMoveTask->SetUp(MyController, FVector::ZeroVector, TargetActor, AcceptableRadius, /*bUsePathfinding=*/false, FAISystem::BoolToAIOption(bStopOnOverlap)); NodeResult = EBTNodeResult::InProgress; } else { UE_VLOG(MyController, LogBehaviorTree, Warning, TEXT("UBTTask_MoveDirectlyToward::ExecuteTask tried to go to actor while BB %s entry was empty"), *BlackboardKey.SelectedKeyName.ToString()); } } else if (BlackboardKey.SelectedKeyType == UBlackboardKeyType_Vector::StaticClass()) { const FVector TargetLocation = MyBlackboard->GetValue<UBlackboardKeyType_Vector>(BlackboardKey.GetSelectedKeyID()); AIMoveTask->SetUp(MyController, TargetLocation, nullptr, AcceptableRadius, /*bUsePathfinding=*/false, FAISystem::BoolToAIOption(bStopOnOverlap)); NodeResult = EBTNodeResult::InProgress; } if (NodeResult == EBTNodeResult::InProgress) { AIMoveTask->ReadyForActivation(); } } } else { EPathFollowingRequestResult::Type RequestResult = EPathFollowingRequestResult::Failed; if (BlackboardKey.SelectedKeyType == UBlackboardKeyType_Object::StaticClass()) { UObject* KeyValue = MyBlackboard->GetValue<UBlackboardKeyType_Object>(BlackboardKey.GetSelectedKeyID()); AActor* TargetActor = Cast<AActor>(KeyValue); if (TargetActor) { RequestResult = bDisablePathUpdateOnGoalLocationChange ? MyController->MoveToLocation(TargetActor->GetActorLocation(), AcceptableRadius, bStopOnOverlap, /*bUsePathfinding=*/false, /*bProjectDestinationToNavigation=*/bProjectVectorGoalToNavigation, bAllowStrafe) : MyController->MoveToActor(TargetActor, AcceptableRadius, bStopOnOverlap, /*bUsePathfinding=*/false, bAllowStrafe); } } else if (BlackboardKey.SelectedKeyType == UBlackboardKeyType_Vector::StaticClass()) { const FVector TargetLocation = MyBlackboard->GetValue<UBlackboardKeyType_Vector>(BlackboardKey.GetSelectedKeyID()); RequestResult = MyController->MoveToLocation(TargetLocation, AcceptableRadius, bStopOnOverlap, /*bUsePathfinding=*/false, /*bProjectDestinationToNavigation=*/bProjectVectorGoalToNavigation, bAllowStrafe); } if (RequestResult == EPathFollowingRequestResult::RequestSuccessful) { const FAIRequestID RequestID = MyController->GetCurrentMoveRequestID(); MyMemory->MoveRequestID = RequestID; WaitForMessage(OwnerComp, UBrainComponent::AIMessage_MoveFinished, RequestID); NodeResult = EBTNodeResult::InProgress; } else if (RequestResult == EPathFollowingRequestResult::AlreadyAtGoal) { NodeResult = EBTNodeResult::Succeeded; } } } return NodeResult; }
void FGameplayDebuggerCategory_AI::CollectData(APlayerController* OwnerPC, AActor* DebugActor) { APawn* MyPawn = Cast<APawn>(DebugActor); ACharacter* MyChar = Cast<ACharacter>(MyPawn); DataPack.PawnName = MyPawn ? MyPawn->GetHumanReadableName() : FString(TEXT("{red}No selected pawn.")); DataPack.bIsUsingCharacter = (MyChar != nullptr); AAIController* MyController = MyPawn ? Cast<AAIController>(MyPawn->Controller) : nullptr; DataPack.bHasController = (MyController != nullptr); if (MyController) { if (MyController->IsPendingKill() == false) { DataPack.ControllerName = MyController->GetName(); } else { DataPack.ControllerName = TEXT("Controller PENDING KILL"); } } else { DataPack.ControllerName = TEXT("No Controller"); } if (MyPawn && !MyPawn->IsPendingKill()) { UCharacterMovementComponent* CharMovementComp = MyChar ? MyChar->GetCharacterMovement() : nullptr; if (CharMovementComp) { UPrimitiveComponent* FloorComponent = MyPawn->GetMovementBase(); AActor* FloorActor = FloorComponent ? FloorComponent->GetOwner() : nullptr; DataPack.MovementBaseInfo = FloorComponent ? FString::Printf(TEXT("%s.%s"), *GetNameSafe(FloorActor), *FloorComponent->GetName()) : FString(TEXT("None")); DataPack.MovementModeInfo = CharMovementComp->GetMovementName(); } UBehaviorTreeComponent* BehaviorComp = MyController ? Cast<UBehaviorTreeComponent>(MyController->BrainComponent) : nullptr; DataPack.bIsUsingBehaviorTree = (BehaviorComp != nullptr); if (BehaviorComp) { DataPack.CurrentAITask = BehaviorComp->DescribeActiveTasks(); DataPack.CurrentAIState = BehaviorComp->IsRunning() ? TEXT("Running") : BehaviorComp->IsPaused() ? TEXT("Paused") : TEXT("Inactive"); DataPack.CurrentAIAssets = BehaviorComp->DescribeActiveTrees(); } UGameplayTasksComponent* TasksComponent = MyController ? MyController->GetGameplayTasksComponent() : nullptr; DataPack.bIsUsingGameplayTasks = (TasksComponent != nullptr); if (TasksComponent) { for (FConstGameplayTaskIterator It = TasksComponent->GetTickingTaskIterator(); It; ++It) { const UGameplayTask* TaskOb = *It; if (TaskOb) { DataPack.TickingTaskInfo += DescribeTaskHelper(*TaskOb); DataPack.NumTickingTasks++; } } for (FConstGameplayTaskIterator It = TasksComponent->GetPriorityQueueIterator(); It; ++It) { const UGameplayTask* TaskOb = *It; if (TaskOb) { DataPack.TaskQueueInfo += DescribeTaskHelper(*TaskOb); DataPack.NumTasksInQueue++; } } } DataPack.MontageInfo = MyChar ? GetNameSafe(MyChar->GetCurrentMontage()) : FString(); UNavigationSystem* NavSys = UNavigationSystem::GetCurrent(MyPawn->GetWorld()); const ANavigationData* NavData = MyController && NavSys ? NavSys->GetNavDataForProps(MyController->GetNavAgentPropertiesRef()) : nullptr; DataPack.NavDataInfo = NavData ? NavData->GetConfig().Name.ToString() : FString(); CollectPathData(MyController); } else { PathDataPack.PathCorridor.Reset(); PathDataPack.PathPoints.Reset(); } }
void C_DudeMoveTo::Cancel() { AAIController* controller = CastChecked<AAIController>(m_Dude.GetController()); controller->StopMovement(); }
bool C_DudeMoveTo::Update(float) { AAIController* controller = CastChecked<AAIController>(m_Dude.GetController()); auto status = controller->GetMoveStatus(); return status != EPathFollowingStatus::Idle; }