Unreal Engine C++ Developer: Learn C++ and Make Video Games | Udemy UE4.26 Simple Shooterで自分なりに理解したこと。01300 ~NavMeshとAIの動き~

NavMeshを配置して

表示できるようにします。

表示されました。

ブラシセッティングで広げます。

BP_ShooterAIControllerを開いてPathFollowingComponentが作用しているからです。

C:\Program Files\Epic Games\UE_4.26\Engine\Source\Runtime\AIModule\Classes\AIController.h

MoveToを見ると

MoveToActor

MoveToLocation

MoveTo

の3つがあります。

	/** AIを指定されたゴールアクターに向けて移動させ(宛先は継続的に更新されます)、
次のアクティブなパスを中止します
* @ paramAcceptanceRadius-ポーンが十分に近づいたら移動を終了します
* @ parambStopOnOverlap-ポーンの半径をAcceptanceRadiusに追加します
* @param bUsePathfinding-ナビゲーションデータを使用してパスを計算します
(そうでない場合は直線になります)
* @param bCanStrafe-フォーカス関連フラグを設定します:bAllowStrafe
* @ paramFilterClass-パスファインディング調整用のナビゲーションフィルター。
指定されていない場合、DefaultNavigationFilterClassが使用されます
* @ parambAllowPartialPath-目標に到達できない場合は不完全なパスを使用します
* @note AcceptanceRadiusは、ヘッダーパーサーが
UPathFollowingComponent :: DefaultAcceptanceRadiusを認識できないため、
デフォルト値または-1になります。*/
	UFUNCTION(BlueprintCallable, Category = "AI|Navigation", Meta = (AdvancedDisplay = "bStopOnOverlap,bCanStrafe,bAllowPartialPath"))
	EPathFollowingRequestResult::Type MoveToActor(AActor* Goal, float AcceptanceRadius = -1, bool bStopOnOverlap = true,
		bool bUsePathfinding = true, bool bCanStrafe = true,
		TSubclassOf<UNavigationQueryFilter> FilterClass = NULL, bool bAllowPartialPath = true);

なので

\ShooterAIController.cpp

// Fill out your copyright notice in the Description page of Project Settings.


#include "ShooterAIController.h"

#include "Kismet\GameplayStatics.h"

void AShooterAIController::BeginPlay()
{
    Super::BeginPlay();
    APawn* PlayerPawn= UGameplayStatics::GetPlayerPawn(GetWorld(),0);

    SetFocus(PlayerPawn);
    MoveToActor(PlayerPawn,200);

}

これでプレイしてみると一度動きます。が一度しかついてきません。

C:\Program Files\Epic Games\UE_4.26\Engine\Source\Runtime\Engine\Classes\GameFramework\Actor.h

	virtual void Tick( float DeltaSeconds );

をコピーしてShooterAIController.hにTickをオーバーライドしてこうしました。

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "AIController.h"
#include "ShooterAIController.generated.h"

/**
 * 
 */
UCLASS()
class SIMPLESHOOTERCP2_API AShooterAIController : public AAIController
{
	GENERATED_BODY()
public:
	virtual void Tick( float DeltaSeconds ) override;

protected:
	virtual void BeginPlay() override;	
};

C:\Download\Game\SImpleShooter\SImpleShooterCp2 4.26\Source\SImpleShooterCp2\ShooterAIController.cpp

// Fill out your copyright notice in the Description page of Project Settings.


#include "ShooterAIController.h"

#include "Kismet\GameplayStatics.h"

void AShooterAIController::BeginPlay()
{
    Super::BeginPlay();
    //APawn* PlayerPawn= UGameplayStatics::GetPlayerPawn(GetWorld(),0);

    
}
void AShooterAIController::Tick(float DeltaSecond)
{
    APawn* PlayerPawn= UGameplayStatics::GetPlayerPawn(GetWorld(),0);
    SetFocus(PlayerPawn);
    MoveToActor(PlayerPawn,200);

}

NavMeshを広げておかないとAIキャラクターが歩きにくいみたいです

できたのがこれ、

AIキャラクターが回転しないバグは次のときに説明するみたい。

Unreal Engine C++ Developer: Learn C++ and Make Video Games | Udemy UE4.26 Simple Shooterで自分なりに理解したこと。01200 ~AI Aimining~

Control + P でAIControllerと入力して

UE_4.26\Engine\Source\Runtime\AIModule\Classes\AIController.h

を開きます。

    /* 特定の優先度にフォーカスアクター設定し、結果としてFocalPointを設定します。*/    virtual void SetFocus(AActor* NewFocus, EAIFocusPriority::Type InPriority = EAIFocusPriority::Gameplay);

/ *特定の優先度にフォーカスアクターを設定し、結果としてFocalPointを設定します。 * /
	/* Set Focus actor for given priority, will set FocalPoint as a result. */
	virtual void SetFocus(AActor* NewFocus, EAIFocusPriority::Type InPriority = EAIFocusPriority::Gameplay);

   

こっちは

指定された優先度のフォーカスをクリアし、結果としてFocalPointもクリアします@paramInPriorityフォーカス優先度をクリアします。 何を使用すればよいかわからない場合は、おそらくEAIFocusPriority :: Gameplay * /を意味します。

  virtual void ClearFocus(EAIFocusPriority::Type InPriority);

	/** 指定された優先度のフォーカスをクリアし、結果としてFocalPointもクリアします
* @paramInPriorityフォーカス優先度をクリアします。 何を使用すればよいかわからない場合は、おそらくEAIFocusPriority :: Gameplay * /を意味します。*/
	virtual void ClearFocus(EAIFocusPriority::Type InPriority);

フォーカスの優先度ってなによってなるので見てみると

その列挙型の定義を見てみると、デフォルトの動きMoveゲームプレイがあることがわかります

そしてそれらは基本的に優先順位の順にリストされています。

//これが通常の列挙型ではなく名前空間である理由は
//ゲーム固有のコードで拡張できるようにする
// @todoこれは少し面倒なので、リファクタリングする必要があります
namespace EAIFocusPriority
{
	typedef uint8 Type;

	const Type Default = 0;
	const Type Move = 1;
	const Type Gameplay = 2;

	const Type LastFocusPriority = Gameplay;
}

struct FFocusKnowledge
{
	struct FFocusItem
	{
		TWeakObjectPtr<AActor> Actor;
		FVector Position;

		FFocusItem()
		{
			Actor = nullptr;
			Position = FAISystem::InvalidLocation;
		}
	};
	
	TArray<FFocusItem> Priorities;
};

私たちは主にこのゲームプレイを使用するので、それらをあまり使用する必要はありませんでした

次に

UE_4.26\Engine\Source\Runtime\Engine\Classes\GameFramework\Actor.h

protected:
	/** Overridable native event for when play begins for this actor. */
	virtual void BeginPlay();

をコピーして

ShooterAIController.hにペーストしてオーバーライドします

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "AIController.h"
#include "ShooterAIController.generated.h"

/**
 * 
 */
UCLASS()
class SIMPLESHOOTERCP2_API AShooterAIController : public AAIController
{
	GENERATED_BODY()
protected:
	virtual void BeginPlay() override;	
};

C:\Program Files\Epic Games\UE_4.26\Engine\Source\Runtime\Engine\Classes\Kismet\GameplayStatics.h

	/** 指定されたプレーヤーインデックスのプレーヤーポーンを返します */
	UFUNCTION(BlueprintPure, Category="Game", meta=(WorldContext="WorldContextObject", UnsafeDuringActorConstruction="true"))
	static class APawn* GetPlayerPawn(const UObject* WorldContextObject, int32 PlayerIndex);

をみると指定されたプレーヤーインデックスのプレーヤーポーンを返しますので

// Fill out your copyright notice in the Description page of Project Settings.


#include "ShooterAIController.h"

#include "Kismet\GameplayStatics.h"

void AShooterAIController::BeginPlay()
{
    Super::BeginPlay();
    APawn* PlayerPawn= UGameplayStatics::GetPlayerPawn(GetWorld(),0);

    SetFocus(PlayerPawn);

}

できたのがこれ

Unreal Engine C++ Developer: Learn C++ and Make Video Games | Udemy UE4.25 Simple Shooterで自分なりに理解したこと。00500 ~ヒットした場所にパーティクル~

UE4/Engine/Source/Runtime/Engine/Classes/Kismet/GameplayStatics.h

static UParticleSystemComponent* SpawnEmitterAtLocation(const UObject* WorldContextObject, UParticleSystem* EmitterTemplate, FVector Location, FRotator Rotation = FRotator::ZeroRotator, FVector Scale = FVector(1.f), bool bAutoDestroy = true, EPSCPoolMethod PoolingMethod = EPSCPoolMethod::None, bool bAutoActivateSystem = true);

デフォルト引数あるやつ消すとこう

static UParticleSystemComponent* SpawnEmitterAtLocation(const UObject* WorldContextObject, UParticleSystem* EmitterTemplate, FVector Location);

をつかった

Gun.hに これを追加して

	UPROPERTY(EditAnyWhere)
	UParticleSystem* ImpactEffect;

Gun.cppに実際にはShotDirection でショット方向をコントロールしてる

FVector ShotDirection = -Rotation.Vector();
UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.Location,ShotDirection.Rotation() );

	if(bSuccess==true)
	{
		UE_LOG(LogTemp,Warning,TEXT("HitWall!! "));
		DrawDebugPoint(GetWorld(), Hit.Location,40.0 ,FColor::Red , bPersistentLines2);
		FVector ShotDirection = -Rotation.Vector();
		UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.Location,ShotDirection.Rotation() );

	}

で作ったプロパティ、ImpactEffectに設定

今回の状態 全文
Gun.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Gun.generated.h"

UCLASS()
class SIMPLESHOOTERCP2_API AGun : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	AGun();

	void PullTrigger();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;
private:
	UPROPERTY(VisibleAnyWhere)
	USceneComponent* Root;

	UPROPERTY(VisibleAnyWhere)
	USkeletalMeshComponent* Mesh;

	UPROPERTY(EditAnyWhere)
	UParticleSystem* MuzzleFlash;

	UPROPERTY(EditAnyWhere)
	UParticleSystem* ImpactEffect;

	UPROPERTY(EditAnyWhere)
	float MaxRange = 1000;
};

Gun.cpp

// Fill out your copyright notice in the Description page of Project Settings.


#include "Gun.h"

#include "Components/SkeletalMeshComponent.h"
#include "Kismet/GameplayStatics.h"
#include "DrawDebugHelpers.h"
// Sets default values
AGun::AGun()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
	SetRootComponent(Root);

	Mesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Mesh"));
	Mesh->SetupAttachment(Root);


}
void AGun::PullTrigger()
{
	UE_LOG(LogTemp,Warning,TEXT("You have been shot!! "));
	//MuzzleFlashSocket
	UGameplayStatics::SpawnEmitterAttached(MuzzleFlash, Mesh, TEXT("MuzzleFlashSocket"));
    
	APawn* OwnerPawn = Cast<APawn>(GetOwner());
	if(OwnerPawn==nullptr)
	{
		return;
	}
	AController* OwnerController= OwnerPawn ->GetController();
	if(OwnerController==nullptr)
	{
		return;
	}
	FVector Location= OwnerPawn->GetActorLocation();
	FRotator Rotation;
	OwnerController->GetPlayerViewPoint(  Location, Rotation );
	FVector End = Location + Rotation.Vector() * MaxRange;
	// TOTO: LineTrace

	float FOVDeg=90;
	float Scale=2.f;
	FColor const& Color=FColor::Blue;
	bool bPersistentLines=true;
	float LifeTime=-1.f;
	uint8 DepthPriority = 0;
	//DrawDebugCamera(GetWorld(), Location, Rotation, FOVDeg, Scale, Color, bPersistentLines, LifeTime, DepthPriority);

	float Size2 = 20.0;
	FColor const& Color2= FColor::Green;
	bool bPersistentLines2 = true;
	float LifeTime2 = -1.f;
	uint8 DepthPriority2 = 0;
	//DrawDebugPoint(GetWorld(), Location,Size2 ,Color2 , bPersistentLines2, LifeTime2, DepthPriority2);
	//DrawDebugPoint(GetWorld(), Location,Size2 ,Color2 , bPersistentLines2);
    //DrawDebugDirectionalArrow(GetWorld(), Location, End, 3.0, FColor::Blue, bPersistentLines);

	FHitResult Hit;
	ECollisionChannel TraceChannel = ECollisionChannel::ECC_GameTraceChannel1;
	bool bSuccess = GetWorld()->LineTraceSingleByChannel(Hit,Location,End,TraceChannel);
	if(bSuccess==true)
	{
		UE_LOG(LogTemp,Warning,TEXT("HitWall!! "));
		//DrawDebugPoint(GetWorld(), Hit.Location,40.0 ,FColor::Red , bPersistentLines2);
		FVector ShotDirection = -Rotation.Vector();
		UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.Location,ShotDirection.Rotation() );

	}
	//DrawDebugPoint(GetWorld(), End,Size2 ,FColor::Red , bPersistentLines2);
}

// Called when the game starts or when spawned
void AGun::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void AGun::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

でできたのがこれ