UEC++ day7

敌人NPC机制

敌人机制分析与需求

  • 新建一个character类来作为敌人,直接建蓝图设置骨骼网格,因为敌人可能多种就不规定死,然后这个敌人肯定需要两个触发器,一个用于大范围巡逻,一个用于是否达到主角近点进行攻击
    在这里插入图片描述
  • 注意我们要避免摄像机被敌人阻挡
  • BaseEnemy.h
// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "BaseEnemy.generated.h"UCLASS()
class UEGAME_API ABaseEnemy : public ACharacter
{GENERATED_BODY()public:// Sets default values for this character's propertiesABaseEnemy();UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AI")class USphereComponent* ChaseVolume;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AI")USphereComponent* AttackVolume;
protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;UFUNCTION()virtual void OnChaseVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);UFUNCTION()virtual void OnChaseVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);UFUNCTION()virtual void OnAttackVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);UFUNCTION()virtual void OnAttackVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
};
  • BaseEnemy.cpp
// Fill out your copyright notice in the Description page of Project Settings.#include "BaseEnemy.h"
#include "Components/SphereComponent.h"
#include "Components/SkeletalMeshComponent.h"
#include "Components/CapsuleComponent.h"
// Sets default values
ABaseEnemy::ABaseEnemy()
{// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;//避免摄像机被敌人给阻挡GetMesh()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore);GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore);ChaseVolume = CreateDefaultSubobject<USphereComponent>(TEXT("ChaseVolume"));ChaseVolume->SetupAttachment(GetRootComponent());ChaseVolume->InitSphereRadius(800.f);ChaseVolume->SetCollisionObjectType(ECollisionChannel::ECC_WorldDynamic);ChaseVolume->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);ChaseVolume->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Overlap);AttackVolume = CreateDefaultSubobject<USphereComponent>(TEXT("AttackVolume"));AttackVolume->SetupAttachment(GetRootComponent());AttackVolume->InitSphereRadius(100.f);AttackVolume->SetCollisionObjectType(ECollisionChannel::ECC_WorldDynamic);AttackVolume->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);AttackVolume->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Overlap);
}// Called when the game starts or when spawned
void ABaseEnemy::BeginPlay()
{Super::BeginPlay();ChaseVolume->OnComponentBeginOverlap.AddDynamic(this, &ABaseEnemy::OnChaseVolumeOverlapBegin);ChaseVolume->OnComponentEndOverlap.AddDynamic(this, &ABaseEnemy::OnChaseVolumeOverlapEnd);AttackVolume->OnComponentBeginOverlap.AddDynamic(this, &ABaseEnemy::OnAttackVolumeOverlapBegin);AttackVolume->OnComponentEndOverlap.AddDynamic(this, &ABaseEnemy::OnAttackVolumeOverlapEnd);}// Called every frame
void ABaseEnemy::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}// Called to bind functionality to input
void ABaseEnemy::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{Super::SetupPlayerInputComponent(PlayerInputComponent);}void ABaseEnemy::OnChaseVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
}void ABaseEnemy::OnChaseVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
}void ABaseEnemy::OnAttackVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
}void ABaseEnemy::OnAttackVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
}
  • 注意虚幻的visibility与camera默认是block
    在这里插入图片描述

部署导航网格

++ Nav Mesh Bounds Volume:导航网格
在这里插入图片描述

  • Nav Modifier Volume:修改导航网格

添加AI模块与创建敌人移动状态枚举

  • 有些组件的使用是需要添加依赖项的就像之前的UMG需要添加到自己的工程目录下的工程名.Build.cs里面,调用AI的模块就需要添加AIModule
    在这里插入图片描述
  • 添加敌人移动状态枚举变量与接近主角的函数
UENUM(BlueprintType)
enum class EEnemyMovementStatus :uint8
{EEMS_Idle			UMETA(DisplayName="Idle"),EEMS_MoveToTarget	UMETA(DisPlayName="MoveToTarget"),EEMS_Attacking		UMETA(DisPlayName="Attacking"),EEMS_Dead			UMETA(DisPlayName="Dead")
};//--------------------------------------------------------------UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Enemy Stats")EEnemyMovementStatus EnemyMovementStatus;
//--------------------------------------------------------------void MoveToTarget(class AMainPlayer* Player);

获取AIController并持有敌人

  • AAIcontroller* AIController所需头文件:#include "AIController.h"
  • 声明AAIController类的指针
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AI")
class AAIController* AIController;
  • 设置持有属性
// Sets default values
ABaseEnemy::ABaseEnemy()
{// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;
//-----------------省略----------------------------------------------//设置持有属性AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned;//初始化默认移动状态EnemyMovementStatus = EEnemyMovementStatus::EEMS_Idle;
}
  • 获取到Controller属性
// Called when the game starts or when spawned
void ABaseEnemy::BeginPlay()
{Super::BeginPlay();
//-----------------省略----------------------------------------------	//拿到ControllerAIController = Cast<AAIController>(GetController());
}

调用MoveTo去追逐Player

  • 逻辑(一):首先在追逐事件中去判断是不是Player如果是就调用追逐函数MoveToTarget
void ABaseEnemy::OnChaseVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){MoveToTarget(Player);}}
}
  • 逻辑(二):MoveToTarget函数中,首先将敌人的枚举移动状态变换为EEMS_MoveToTarget,然后判断AIController是否获取成功,成功就去调用MoveTo去追逐主角
  • FAIMoveRequest 是UE中的一个结构体,主要用于指定人工智能(AI)代理的移动请求。其内部包含了一系列参数,如目标位置、到达速度、抵达距离、是否允许短路等等,这些参数都可以用来控制 AI 代理的移动行为。
    当调用 AAIController::MoveTo() 或者 AAIController::SimpleMoveTo() 等函数时,会创建并返回一个 FAIMoveRequest 结构体实例。然后你可以设置它的参数,并将它传递给 AAIController::UpdateMoveStatus() 函数,从而让 AI 代理按照你的要求进行移动。
    总的来说,FAIMoveRequest 提供了一种方便的方式来指定和调整 AI 代理的移动请求,使得 AI 的行为更加灵活多样。
    FAIMoveRequest MoveRequest;
    MoveRequest.SetGoalActor(Player);//设置移动请求目标
    MoveRequest.SetAcceptanceRadius(10.f);	//设置移动半径
    
  • 在UE中,FNavPathSharedPtr NavPath 表示一个智能指针,用于存储和管理导航路径。智能指针是一个类模板,可以自动管理所指向对象的生命周期,避免了因忘记释放内存而导致的内存泄漏问题。
    具体来说,FNavPathSharedPtr 是一个 shared_ptr 类型的智能指针,它指向的是一个 FNavPath 对象。FNavPath 是 Unreal Engine 中的一个类,用于表示从起点到终点的一条导航路径。
    因此,在虚幻引擎中,NavPath 可以用来保存和操作导航路径。例如,可以使用它来获取路径的距离、方向等信息,或者更新路径以适应场景的变化。
    FNavPathSharedPtr NavPath;//会返回路径
    
  • 调用MoveTo去追逐主角
void ABaseEnemy::MoveToTarget(AMainPlayer* Player)
{EnemyMovementStatus = EEnemyMovementStatus::EEMS_MoveToTarget;if (AIController){FAIMoveRequest MoveRequest;MoveRequest.SetGoalActor(Player);//设置移动请求目标MoveRequest.SetAcceptanceRadius(10.f);	//设置移动半径FNavPathSharedPtr NavPath;//会返回路径AIController->MoveTo(MoveRequest, &NavPath);}
}
  • 逻辑(三):当主角出了追逐移动事件就停止移动
void ABaseEnemy::OnChaseVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){if (AIController){//停止移动AIController->StopMovement();}}}
}

创建敌人动画蓝图

  • 基本与创建MainPlayer动画蓝图差不多
  • EnemyAnimInstance,h
// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "Animation/AnimInstance.h"
#include "EnemyAnimInstance.generated.h"/*** */
UCLASS()
class UEGAME_API UEnemyAnimInstance : public UAnimInstance
{GENERATED_BODY()
public:UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Animation Properties")float Speed;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Animation Properties")class ABaseEnemy* Enemy;virtual void NativeInitializeAnimation() override;UFUNCTION(BlueprintCallable, Category = "Animaion Properties")void UpDataAnimationProperties();
};
  • EnemyAnimInstance.cpp
// Fill out your copyright notice in the Description page of Project Settings.#include "EnemyAnimInstance.h"
#include "Animation/AnimInstance.h"
#include "Characters/Enemy/BaseEnemy.h"void UEnemyAnimInstance::NativeInitializeAnimation()
{Enemy = Cast<ABaseEnemy>(TryGetPawnOwner());
}void UEnemyAnimInstance::UpDataAnimationProperties()
{if (Enemy){Enemy = Cast<ABaseEnemy>(TryGetPawnOwner());}if (Enemy){FVector SpeedVector = Enemy->GetVelocity();FVector PlanarSpeed = FVector(SpeedVector.X, SpeedVector.Y, 0.f);Speed = PlanarSpeed.Size();}
}
  • 创建动画蓝图
    在这里插入图片描述

敌人行走的混合空间

  • 基本和当时创建Player的混合空间差不多
    在这里插入图片描述
  • 编写动画蓝图
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
  • 然后设置到蓝图上即可
    在这里插入图片描述

创建蒙太奇以及攻击编码

  • 创建蒙太奇
    在这里插入图片描述
  • 攻击逻辑:老规矩引用一个bool变量用于检测是否在攻击范围,新建Montage引用后续方便调用Montage功能,与两个函数用来攻击和攻击结束的逻辑编写,攻击结束要在蓝图中调用加上反射,在重叠事件中写是否检测到主角进入攻击范围如果是就执行攻击函数,攻击函数中首先关闭移动,然后判断是不是正在攻击(默认肯定没有攻击,所以判断完要设定为正在攻击),然后获取AnimInstance进行片段播放,攻击结束函数逻辑就先把状态变为待机状态,然后判断是否在攻击范围bool变量,如果为真就继续执行攻击函数形成闭环,最后离开了重叠事件范围就先把bool检测攻击变为false,判断攻击状态是否结束,如果结束就继续执行追逐主角函数,可能这个逻辑会导致bug,所以我们把追逐主角的函数MoveToTarget添加反射到时候在蓝图中完善
  • 需要的变量与函数
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Attack")bool bAttackVolumeOverlap;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")class UAnimMontage* AttackMontage;UFUNCTION(BlueprintCallable)
void MoveToTarget(class AMainPlayer* Player);
void AttackBegin();
UFUNCTION(BlueprintCallable)
void AttackEnd();
  • 函数逻辑
void ABaseEnemy::OnChaseVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){MoveToTarget(Player);}}
}void ABaseEnemy::OnChaseVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){if (AIController){//停止移动AIController->StopMovement();}}}
}void ABaseEnemy::OnAttackVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){bAttackVolumeOverlap = true;AttackBegin();}}
}void ABaseEnemy::OnAttackVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){bAttackVolumeOverlap = false;if (EnemyMovementStatus!=EEnemyMovementStatus::EEMS_Attacking){MoveToTarget(Player);}}}
}void ABaseEnemy::MoveToTarget(AMainPlayer* Player)
{EnemyMovementStatus = EEnemyMovementStatus::EEMS_MoveToTarget;if (AIController){FAIMoveRequest MoveRequest;MoveRequest.SetGoalActor(Player);//设置移动请求目标MoveRequest.SetAcceptanceRadius(10.f);	//设置移动半径FNavPathSharedPtr NavPath;//会返回路径AIController->MoveTo(MoveRequest, &NavPath);}
}void ABaseEnemy::AttackBegin()
{//攻击中关闭移动if (AIController){AIController->StopMovement();}if (EnemyMovementStatus != EEnemyMovementStatus::EEMS_Attacking){EnemyMovementStatus = EEnemyMovementStatus::EEMS_Attacking;UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();if (AnimInstance && AttackMontage){float PlayRate = FMath::RandRange(0.9f, 1.1f);FString SectionName = FString::FromInt(FMath::RandRange(1, 3));AnimInstance->Montage_Play(AttackMontage, PlayRate);AnimInstance->Montage_JumpToSection(FName(*SectionName), AttackMontage);}}
}void ABaseEnemy::AttackEnd()
{EnemyMovementStatus = EEnemyMovementStatus::EEMS_Idle;if (bAttackVolumeOverlap){AttackBegin();}
}

攻击动画的编写以及连续追逐

  • 首先把Montage的攻击通知加上,然后在动画蓝图里面添加蒙太奇
    在这里插入图片描述
    在这里插入图片描述
  • 然后在事件图表里面进行编辑,调用通知AttackEnd事件执行AttackEnd函数,然后进行判断主角离开了攻击重叠事件的判断,如果离开了,就又继续执行追逐主角函数
    在这里插入图片描述

敌人更新攻击目标

  • 思想:近点跟随,谁离得近就先攻击谁
  • 在MainPlayer中新建一个敌人类的指针引用与一个模版敌人类,一个更新攻击目标的函数
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Attack")class ABaseEnemy* AttackTarget;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")TSubclassOf<ABaseEnemy> EnemyFilter;
//-----------------------------------------------------------------
void UpdataAttackTarget();
  • 定义一个模版敌人类就是因为要使用这个函数GetOverlappingActors:它能够获取与指定组件相交的所有 Actors 列表,在使用时记得加上敌人类头文件,避免不知道EnemyFilter
void AMainPlayer::UpdataAttackTarget()
{TArray<AActor*> OVerlappingActors;GetOverlappingActors(OVerlappingActors,EnemyFilter);
}
  • 在返回的相交所有Actor列表里面进行选择最近的那个,逻辑是:遍历OverlapingActors数组进行比较,近的就替换远的。新建一个用于交换的敌人类引用,新建一个最小范围,然后获取当前位置,然后开始变量数组,将数组里面的单位全部转换为敌人类,判断敌人是否存在是否死亡,如果存在无死亡就当前距离主角的位置记录下来,如果距离主角位置小于最小范围那么就将距离主角位置赋值最小范围,将当前敌人类给交换敌人的引用,循环结束就将当前距离主角位置赋值给AttackTarget
void AMainPlayer::UpdataAttackTarget()
{TArray<AActor*> OVerlappingActors;GetOverlappingActors(OVerlappingActors,EnemyFilter);//判断列表里面是否为空,为空就无攻击目标if (OVerlappingActors.Num() == 0){AttackTarget = nullptr;return;}ABaseEnemy* ClosestDistance = nullptr;float MinDistance = 1000.f;FVector Loation = GetActorLocation();for (auto Actor : OVerlappingActors){ABaseEnemy* Enemy = Cast<ABaseEnemy>(Actor);if (Enemy && Enemy->EnemyMovementStatus != EEnemyMovementStatus::EEMS_Dead){float DistanceToActor = (Enemy->GetActorLocation() - Loation).Size();//记录当前位置Enemy距离MainPlayer位置if (DistanceToActor < MinDistance){MinDistance = DistanceToActor;ClosestDistance = Enemy;}}}AttackTarget = ClosestDistance;
}
  • 然后在BaseEnemy类的攻击碰撞事件中调用此函数
void ABaseEnemy::OnAttackVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){Player->UpdataAttackTarget();bAttackVolumeOverlap = true;AttackBegin();}}
}

玩家自动面向攻击目标

  • 采用插值的思想方法,当我们需要攻击转向时就进行插值转向
  • 在MainPlayer类中新建一个插值速度变量与一个bool是否进行插值变量并赋初值
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")float InterpSpeed;UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Attack")bool bInterpToEnemy;InterpSpeed = 15.f;
bInterpToEnemy = false;
  • 然后在攻击函数中将bool插值变量赋为true,攻击结束函数中设为false
void AMainPlayer::AttackBegin()
{if (!bIsAttacking){bIsAttacking = true;bInterpToEnemy = true;//拿到动画UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();if (AnimInstance && AttackMontage){float PlayRate = FMath::RandRange(1.25f, 1.75f);FString SectionName = FString::FromInt(FMath::RandRange(1, 2));//指定片段播放AnimInstance->Montage_Play(AttackMontage, PlayRate);AnimInstance->Montage_JumpToSection(FName(*SectionName), AttackMontage);}}
}void AMainPlayer::AttackEnd()
{bIsAttacking = false;bInterpToEnemy = false;//形成闭环if (bAttackKeyDown){AttackKeyDown();}
}
  • 然后去Tick里面进行转向逻辑编写,使用RInterpTo要头文件:#include “Kismet/KismetMathLibrary.h”
//进行转向插值if (bInterpToEnemy && AttackTarget){//只需要AttackTarget的Yaw转向FRotator LookAtYaw(0.f, UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), AttackTarget->GetActorLocation()).Yaw, 0.f);FRotator InterpRotation = FMath::RInterpTo(GetActorRotation(), LookAtYaw, DeltaTime, InterpSpeed);SetActorRotation(InterpRotation);}
  • 将Enemy给过滤器,必须是C++类
    在这里插入图片描述

敌人自动面向玩家攻击目标

  • 基本与玩家面向攻击目标的编写差不多
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")float InterpSpeed;UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Attack")bool bInterpToPlayer;InterpSpeed = 15.f;
bInterpToPlayer = false;
  • 然后在攻击函数中将bool插值变量赋为true,攻击结束函数中设为false
void ABaseEnemy::AttackBegin()
{//攻击中关闭移动if (AIController){AIController->StopMovement();}if (EnemyMovementStatus != EEnemyMovementStatus::EEMS_Attacking){EnemyMovementStatus = EEnemyMovementStatus::EEMS_Attacking;bInterpToPlayer = true;UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();if (AnimInstance && AttackMontage){float PlayRate = FMath::RandRange(0.9f, 1.1f);FString SectionName = FString::FromInt(FMath::RandRange(1, 3));AnimInstance->Montage_Play(AttackMontage, PlayRate);AnimInstance->Montage_JumpToSection(FName(*SectionName), AttackMontage);}}
}void ABaseEnemy::AttackEnd()
{EnemyMovementStatus = EEnemyMovementStatus::EEMS_Idle;bInterpToPlayer = false;if (bAttackVolumeOverlap){AttackBegin();}
}
  • 然后去Tick里面进行转向逻辑编写,注意的事FindLookAtRotation中的目标位置是Player,得去获取位置,获取位置要加头文件:#include "Kismet/GameplayStatics.h",使用RInterpTo也要头文件:#include "Kismet/KismetMathLibrary.h"
void ABaseEnemy::Tick(float DeltaTime)
{Super::Tick(DeltaTime);if (bInterpToPlayer){FRotator LookYaw(0.f, UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), UGameplayStatics::GetPlayerPawn(this, 0)->GetActorLocation()).Yaw, 0.f);FRotator InterpRotation = FMath::RInterpTo(GetActorRotation(), LookYaw, DeltaTime, InterpSpeed);SetActorRotation(InterpRotation);}
}

BaseEnemy.h

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "BaseEnemy.generated.h"UENUM(BlueprintType)
enum class EEnemyMovementStatus :uint8
{EEMS_Idle			UMETA(DisplayName="Idle"),EEMS_MoveToTarget	UMETA(DisPlayName="MoveToTarget"),EEMS_Attacking		UMETA(DisPlayName="Attacking"),EEMS_Dead			UMETA(DisPlayName="Dead")
};UCLASS()
class UEGAME_API ABaseEnemy : public ACharacter
{GENERATED_BODY()public:// Sets default values for this character's propertiesABaseEnemy();UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AI")class USphereComponent* ChaseVolume;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AI")USphereComponent* AttackVolume;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AI")class AAIController* AIController;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Enemy Stats")EEnemyMovementStatus EnemyMovementStatus;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Attack")bool bAttackVolumeOverlap;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")class UAnimMontage* AttackMontage;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")float InterpSpeed;UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Attack")bool bInterpToPlayer;
protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;UFUNCTION()virtual void OnChaseVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);UFUNCTION()virtual void OnChaseVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);UFUNCTION()virtual void OnAttackVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);UFUNCTION()virtual void OnAttackVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);UFUNCTION(BlueprintCallable)void MoveToTarget(class AMainPlayer* Player);void AttackBegin();UFUNCTION(BlueprintCallable)void AttackEnd();
};

BaseEnemy.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "BaseEnemy.h"
#include "Components/SphereComponent.h"
#include "Components/SkeletalMeshComponent.h"
#include "Components/CapsuleComponent.h"
#include "AIController.h"
#include "Characters/Player/MainPlayer.h"
#include "Animation/AnimInstance.h"
#include "Kismet/KismetMathLibrary.h"
#include "Kismet/GameplayStatics.h"
// Sets default values
ABaseEnemy::ABaseEnemy()
{// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;ChaseVolume = CreateDefaultSubobject<USphereComponent>(TEXT("ChaseVolume"));ChaseVolume->SetupAttachment(GetRootComponent());ChaseVolume->InitSphereRadius(800.f);ChaseVolume->SetCollisionObjectType(ECollisionChannel::ECC_WorldDynamic);ChaseVolume->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);ChaseVolume->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Overlap);AttackVolume = CreateDefaultSubobject<USphereComponent>(TEXT("AttackVolume"));AttackVolume->SetupAttachment(GetRootComponent());AttackVolume->InitSphereRadius(100.f);AttackVolume->SetCollisionObjectType(ECollisionChannel::ECC_WorldDynamic);AttackVolume->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);AttackVolume->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Overlap);//避免摄像机被敌人给阻挡GetMesh()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore);GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore);//设置持有属性AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned;//初始化默认移动状态EnemyMovementStatus = EEnemyMovementStatus::EEMS_Idle;InterpSpeed = 15.f;bInterpToPlayer = false;
}// Called when the game starts or when spawned
void ABaseEnemy::BeginPlay()
{Super::BeginPlay();ChaseVolume->OnComponentBeginOverlap.AddDynamic(this, &ABaseEnemy::OnChaseVolumeOverlapBegin);ChaseVolume->OnComponentEndOverlap.AddDynamic(this, &ABaseEnemy::OnChaseVolumeOverlapEnd);AttackVolume->OnComponentBeginOverlap.AddDynamic(this, &ABaseEnemy::OnAttackVolumeOverlapBegin);AttackVolume->OnComponentEndOverlap.AddDynamic(this, &ABaseEnemy::OnAttackVolumeOverlapEnd);//拿到ControllerAIController = Cast<AAIController>(GetController());
}// Called every frame
void ABaseEnemy::Tick(float DeltaTime)
{Super::Tick(DeltaTime);if (bInterpToPlayer){FRotator LookYaw(0.f, UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), UGameplayStatics::GetPlayerPawn(this, 0)->GetActorLocation()).Yaw, 0.f);FRotator InterpRotation = FMath::RInterpTo(GetActorRotation(), LookYaw, DeltaTime, InterpSpeed);SetActorRotation(InterpRotation);}
}// Called to bind functionality to input
void ABaseEnemy::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{Super::SetupPlayerInputComponent(PlayerInputComponent);}void ABaseEnemy::OnChaseVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){MoveToTarget(Player);}}
}void ABaseEnemy::OnChaseVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){if (AIController){//停止移动AIController->StopMovement();}}}
}void ABaseEnemy::OnAttackVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){Player->UpdataAttackTarget();bAttackVolumeOverlap = true;AttackBegin();}}
}void ABaseEnemy::OnAttackVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{if (OtherActor){AMainPlayer* Player = Cast<AMainPlayer>(OtherActor);if (Player){bAttackVolumeOverlap = false;if (EnemyMovementStatus!=EEnemyMovementStatus::EEMS_Attacking){MoveToTarget(Player);}}}
}void ABaseEnemy::MoveToTarget(AMainPlayer* Player)
{EnemyMovementStatus = EEnemyMovementStatus::EEMS_MoveToTarget;if (AIController){FAIMoveRequest MoveRequest;MoveRequest.SetGoalActor(Player);//设置移动请求目标MoveRequest.SetAcceptanceRadius(10.f);	//设置移动半径FNavPathSharedPtr NavPath;//会返回路径AIController->MoveTo(MoveRequest, &NavPath);}
}void ABaseEnemy::AttackBegin()
{//攻击中关闭移动if (AIController){AIController->StopMovement();}if (EnemyMovementStatus != EEnemyMovementStatus::EEMS_Attacking){EnemyMovementStatus = EEnemyMovementStatus::EEMS_Attacking;bInterpToPlayer = true;UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();if (AnimInstance && AttackMontage){float PlayRate = FMath::RandRange(0.9f, 1.1f);FString SectionName = FString::FromInt(FMath::RandRange(1, 3));AnimInstance->Montage_Play(AttackMontage, PlayRate);AnimInstance->Montage_JumpToSection(FName(*SectionName), AttackMontage);}}
}void ABaseEnemy::AttackEnd()
{EnemyMovementStatus = EEnemyMovementStatus::EEMS_Idle;bInterpToPlayer = false;if (bAttackVolumeOverlap){AttackBegin();}
}

MainPlayer.h

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "MainPlayer.generated.h"//声明移动状态枚举
UENUM(BlueprintType)
enum class EPlayerMovementStatus :uint8
{EPMS_Normal UMETA(DisplayName = "Normal"),EPMS_Sprinting UMETA(DisplayName = "Sprinting"),EPMS_Dead UMETA(DisplayName = "Dead")
};UENUM(BlueprintType)
enum class EPlayerStaminaStatus :uint8
{EPSS_Normal UMETA(DisplayName = "Normal"),EPSS_Exhausted UMETA(DisplayName = "Exhausted"),EPSS_ExhaustedRecovering UMETA(DisplayName = "ExhaustedRecovering")
};UCLASS()
class UEGAME_API AMainPlayer : public ACharacter
{GENERATED_BODY()public:// Sets default values for this character's propertiesAMainPlayer();//新建一个SpringArmUPROPERTY(visibleAnywhere,BlueprintReadOnly)class USpringArmComponent* SpringArm;//新建一个CameraUPROPERTY(visibleAnywhere, BlueprintReadOnly)class UCameraComponent* FollowCamera;float BaseTurnRate;		//使用键盘X转向的速率float BaseLookUpRate;	//使用键盘Y转向的速率//主角状态UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Playe State")float Health;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Playe State")float MaxHealth;UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Playe State")float Stamina;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Playe State")float MaxStamina;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Playe State")float StaminaConsumeRate;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Playe State", meta = (ClampMin = 0, ClampMax = 1))float ExhaustedStamina;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Playe State")int Coins;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Player State")float RunningSpeed;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Player State")float SprintSpeed;UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="Player State")EPlayerMovementStatus MovementStatus;UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="Player State")EPlayerStaminaStatus StaminaStatus;bool bLeftShiftDown;//检测是否持剑UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Weapon")bool bIsWeapon;//正在装备的武器UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Weapon")class AWeaponItem* EquipWeapon;//正在重叠的武器UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Weapon")AWeaponItem* OverlapWeapon;bool bAttackKeyDown;//是否按下攻击键UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Animation")bool bIsAttacking;UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Animation")class UAnimMontage* AttackMontage;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Attack")class ABaseEnemy* AttackTarget;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")TSubclassOf<ABaseEnemy> EnemyFilter;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")float InterpSpeed;UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Attack")bool bInterpToEnemy;
protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;//重新Character类中的Jump方法void Jump() override;void MoveForward(float value);void MoveRight(float value);void Turn(float Value);void LookUp(float Value);void TurnRate(float Rate);void LookUpRate(float Rate);//改变状态UFUNCTION(BlueprintCallable,Category="Player|State")void AddHealth(float value);UFUNCTION(BlueprintCallable, Category = "Player|State")void AddStamina(float value);UFUNCTION(BlueprintCallable, Category = "Player|State")void AddCoin(float value);//重写TakeDamage方法float TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) override;//短小精悍FORCEINLINE void LeftShiftDown() { bLeftShiftDown = true; }FORCEINLINE void LeftShiftUp() { bLeftShiftDown = false; }void SetMovementStatus(EPlayerMovementStatus Status);void InteractKeyDown();void AttackKeyDown();FORCEINLINE void AttackKeyUp() { bAttackKeyDown = false; }void AttackBegin();UFUNCTION(BlueprintCallable)void AttackEnd();void UpdataAttackTarget();
};

MainPlayer.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "MainPlayer.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/PlayerController.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GamePlay/WeaponItem.h"
#include "Animation/AnimInstance.h"
#include "Characters/Enemy/BaseEnemy.h"
#include "Kismet/KismetMathLibrary.h"
// Sets default values
AMainPlayer::AMainPlayer()
{// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));SpringArm->SetupAttachment(GetRootComponent());//设置SPringArm无碰撞臂长SpringArm->TargetArmLength = 600.f;SpringArm->bUsePawnControlRotation = true;//硬编码SpringArm继承controlller旋转为真FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));FollowCamera->SetupAttachment(SpringArm, NAME_None);FollowCamera->bUsePawnControlRotation = false;//硬编码FollowCamera继承controlller旋转为假//设置胶囊体的默认宽高GetCapsuleComponent()->SetCapsuleSize(35.f, 100.f);//对Character的Pawn进行硬编码bUseControllerRotationPitch = false;bUseControllerRotationYaw = false;bUseControllerRotationRoll = false;//硬编码orient Rotation to Movement,给个默认转向速率GetCharacterMovement()->bOrientRotationToMovement = true;GetCharacterMovement()->RotationRate = FRotator(0.f, 500.f, 0.f);//设置跳跃初始值与在空中的坠落时横向运动控制量GetCharacterMovement()->JumpZVelocity = 400.f;GetCharacterMovement()->AirControl = 0.15f;//给键盘控制转向的速率变量赋初值BaseTurnRate = 21.f;BaseLookUpRate = 21.f;//初始化角色状态MaxHealth = 100.f;Health = MaxHealth;MaxStamina = 200.f;Stamina = MaxStamina;StaminaConsumeRate = 20.f;ExhaustedStamina = 0.167f;Coins = 0;RunningSpeed = 600.f;SprintSpeed = 900.f;MovementStatus = EPlayerMovementStatus::EPMS_Normal;StaminaStatus = EPlayerStaminaStatus::EPSS_Normal;//默认没有按下shiftbLeftShiftDown = false;InterpSpeed = 15.f;bInterpToEnemy = false;
}// Called when the game starts or when spawned
void AMainPlayer::BeginPlay()
{Super::BeginPlay();
}// Called every frame
void AMainPlayer::Tick(float DeltaTime)
{Super::Tick(DeltaTime);switch (StaminaStatus){case EPlayerStaminaStatus::EPSS_Normal://当Shift按下if (bLeftShiftDown){if (Stamina - StaminaConsumeRate * DeltaTime <= MaxStamina * ExhaustedStamina){StaminaStatus = EPlayerStaminaStatus::EPSS_Exhausted;}//无论是不是精疲力尽状态都要减去当前帧冲刺消耗的耐力Stamina -= StaminaConsumeRate * DeltaTime;SetMovementStatus(EPlayerMovementStatus::EPMS_Sprinting);}else{//当Shift没有按下,恢复耐力Stamina = FMath::Clamp(Stamina + StaminaConsumeRate * DeltaTime, 0.f, MaxStamina);SetMovementStatus(EPlayerMovementStatus::EPMS_Normal);}break;case EPlayerStaminaStatus::EPSS_Exhausted:if (bLeftShiftDown){//如果耐力已经为0if (Stamina - StaminaConsumeRate * DeltaTime <= 0.f){//么我们需要内部编码把shift抬起,此时StaminaStatus状态转换为ExhaustedRecovering状态,然后设置移动状态为NormalLeftShiftUp();StaminaStatus = EPlayerStaminaStatus::EPSS_ExhaustedRecovering;	SetMovementStatus(EPlayerMovementStatus::EPMS_Normal);}else{Stamina -= StaminaConsumeRate * DeltaTime;}}else{StaminaStatus = EPlayerStaminaStatus::EPSS_ExhaustedRecovering;Stamina = FMath::Clamp(Stamina + StaminaConsumeRate * DeltaTime, 0.f, MaxStamina);SetMovementStatus(EPlayerMovementStatus::EPMS_Normal);}break;case EPlayerStaminaStatus::EPSS_ExhaustedRecovering://当恢复大于疲劳区时,StaminaStatus状态为Normalif (Stamina + StaminaConsumeRate * DeltaTime >= MaxStamina * ExhaustedStamina){StaminaStatus = EPlayerStaminaStatus::EPSS_Normal;}//这状态值肯定是加定了Stamina += StaminaConsumeRate * DeltaTime;//抬起shiftLeftShiftUp();SetMovementStatus(EPlayerMovementStatus::EPMS_Normal);break;default:break;}//进行转向插值if (bInterpToEnemy && AttackTarget){//只需要AttackTarget的Yaw转向FRotator LookAtYaw(0.f, UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), AttackTarget->GetActorLocation()).Yaw, 0.f);FRotator InterpRotation = FMath::RInterpTo(GetActorRotation(), LookAtYaw, DeltaTime, InterpSpeed);SetActorRotation(InterpRotation);}
}// Called to bind functionality to input
void AMainPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{Super::SetupPlayerInputComponent(PlayerInputComponent);//检查PlayerInputComponent指针,check函数只能在这使用check(PlayerInputComponent);//绑定跳跃轴映射事件PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AMainPlayer::Jump);//按下空格PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);//抬起空格PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &AMainPlayer::LeftShiftDown);//按下shiftPlayerInputComponent->BindAction("Sprint", IE_Released, this, &AMainPlayer::LeftShiftUp);//抬起shift//拾取剑PlayerInputComponent->BindAction("Interact", IE_Pressed, this, &AMainPlayer::InteractKeyDown);//按下F//攻击PlayerInputComponent->BindAction("Attack", IE_Pressed, this, &AMainPlayer::AttackKeyDown);PlayerInputComponent->BindAction("Attack", IE_Released, this, &AMainPlayer::AttackKeyUp);//绑定移动轴映射事件PlayerInputComponent->BindAxis("MoveForward", this, &AMainPlayer::MoveForward);PlayerInputComponent->BindAxis("MoveRight", this, &AMainPlayer::MoveRight);//绑定Controller控制器去管理视角旋转PlayerInputComponent->BindAxis("Turn", this, &AMainPlayer::Turn);PlayerInputComponent->BindAxis("LookUp", this, &AMainPlayer::LookUp);//绑定键盘鼠标轴映射事件PlayerInputComponent->BindAxis("TurnRate", this, &AMainPlayer::TurnRate);PlayerInputComponent->BindAxis("LookUpRate", this, &AMainPlayer::LookUpRate);}void AMainPlayer::Jump()
{//继承父类的方法Super::Jump();
}void AMainPlayer::MoveForward(float value)
{if (Controller != nullptr && value != 0.f && !(bIsAttacking)){//获取到Control旋转FRotator Rotation = Controller->GetControlRotation();//转向只关注水平Yaw方向,因此置0防止影响FRotator YowRotation = FRotator(0.0f, Rotation.Yaw, 0.0f);//获取相机(鼠标控制器的朝向),并且朝这个轴的方向移动FVector Direction = FRotationMatrix(YowRotation).GetUnitAxis(EAxis::X);AddMovementInput(Direction, value);}}void AMainPlayer::MoveRight(float value)
{if (Controller != nullptr && value != 0.f && !(bIsAttacking)){//获取到Controller旋转FRotator Rotation = Controller->GetControlRotation();//转向只关注水平Yaw方向,因此置0防止影响FRotator YowRotation = FRotator(0.0f, Rotation.Yaw, 0.0f);//获取相机(鼠标控制器的朝向),并且朝这个轴的方向移动FVector Direction = FRotationMatrix(YowRotation).GetUnitAxis(EAxis::Y);AddMovementInput(Direction, value);}
}void AMainPlayer::Turn(float Value)
{if (Value != 0.f){AddControllerYawInput(Value);}}void AMainPlayer::LookUp(float Value)
{//UE_LOG(LogTemp, Warning, TEXT("%f"), GetControlRotation().Pitch);//控制视角if (GetControlRotation().Pitch < 270.f && GetControlRotation().Pitch >180.f && Value > 0.f){return;}else if (GetControlRotation().Pitch < 180.f && GetControlRotation().Pitch >45.f && Value < 0.f){return;}AddControllerPitchInput(Value);
}void AMainPlayer::TurnRate(float Rate)
{//要乘以一个DeltaTime这样就可以避免高帧底帧差值问题float Value = Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds();if (Value != 0.f){AddControllerYawInput(Value);}
}void AMainPlayer::LookUpRate(float Rate)
{//要乘以一个DeltaTime这样就可以避免高帧底帧差值问题float Value = Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds();//控制视角if (GetControlRotation().Pitch < 270.f && GetControlRotation().Pitch >180.f && Value > 0.f){return;}else if (GetControlRotation().Pitch < 180.f && GetControlRotation().Pitch >45.f && Value < 0.f){return;}AddControllerPitchInput(Value);}void AMainPlayer::AddHealth(float value)
{Health = FMath::Clamp(Health + value, 0.f, MaxHealth);
}void AMainPlayer::AddStamina(float value)
{Stamina = FMath::Clamp(Stamina + value, 0.f, MaxStamina);
}void AMainPlayer::AddCoin(float value)
{Coins += value;
}float AMainPlayer::TakeDamage(float Damage, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{if (Health - Damage <= 0.f){Health = FMath::Clamp(Health - Damage, 0.f, MaxHealth);//TODO Die();}else{Health -= Damage;}return Health;
}void AMainPlayer::SetMovementStatus(EPlayerMovementStatus Status)
{MovementStatus = Status;//切换状态的时候改变移动速度switch (MovementStatus){case EPlayerMovementStatus::EPMS_Sprinting:GetCharacterMovement()->MaxWalkSpeed = SprintSpeed;break;default:GetCharacterMovement()->MaxWalkSpeed = RunningSpeed;break;}
}void AMainPlayer::InteractKeyDown()
{if (OverlapWeapon){if (EquipWeapon){//交换武器EquipWeapon->UnEuip(this);OverlapWeapon->Equip(this);}else{//装备武器OverlapWeapon->Equip(this);}}else{if (EquipWeapon){//卸载武器EquipWeapon->UnEuip(this);}}
}void AMainPlayer::AttackKeyDown()
{bAttackKeyDown = true;if (bIsWeapon){AttackBegin();}}void AMainPlayer::AttackBegin()
{if (!bIsAttacking){bIsAttacking = true;bInterpToEnemy = true;//拿到动画UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();if (AnimInstance && AttackMontage){float PlayRate = FMath::RandRange(1.25f, 1.75f);FString SectionName = FString::FromInt(FMath::RandRange(1, 2));//指定片段播放AnimInstance->Montage_Play(AttackMontage, PlayRate);AnimInstance->Montage_JumpToSection(FName(*SectionName), AttackMontage);}}
}void AMainPlayer::AttackEnd()
{bIsAttacking = false;bInterpToEnemy = false;//形成闭环if (bAttackKeyDown){AttackKeyDown();}
}void AMainPlayer::UpdataAttackTarget()
{TArray<AActor*> OVerlappingActors;GetOverlappingActors(OVerlappingActors,EnemyFilter);//判断列表里面是否为空,为空就无攻击目标if (OVerlappingActors.Num() == 0){AttackTarget = nullptr;return;}ABaseEnemy* ClosestDistance = nullptr;float MinDistance = 1000.f;FVector Loation = GetActorLocation();for (auto Actor : OVerlappingActors){ABaseEnemy* Enemy = Cast<ABaseEnemy>(Actor);if (Enemy && Enemy->EnemyMovementStatus != EEnemyMovementStatus::EEMS_Dead){float DistanceToActor = (Enemy->GetActorLocation() - Loation).Size();//记录当前位置Enemy距离MainPlayer位置if (DistanceToActor < MinDistance){MinDistance = DistanceToActor;ClosestDistance = Enemy;}}}AttackTarget = ClosestDistance;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/156882.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Flink】Process Function

目录 1、ProcessFunction解析 1.1 抽象方法.processElement() 1.2 非抽象方法.onTimer() 2、Flink中8个不同的处理函数 2.1 ProcessFunction 2.2 KeyedProcessFunction 2.3 ProcessWindowFunction 2.4 ProcessAllWindowFunction 2.5 CoProcessFunction 2.6 ProcessJo…

https和http的区别和优势

大家好&#xff0c;我是咕噜-凯撒&#xff0c;HTTP&#xff08;超文本传输协议&#xff09;和HTTPS&#xff08;安全超文本传输协议&#xff09;是用于在网络上传输数据的协议&#xff0c;HTTPS相比HTTP在数据传输过程中更加安全可靠&#xff0c;适合对数据安全性要求较高的场景…

ventoy安装操作系统

下载ventoy https://github.com/ventoy/Ventoy/releases/download/v1.0.96/ventoy-1.0.96-windows.zip 解压后执行 Ventoy2Disk 2、安装后将ISO放入U盘大的分区&#xff0c;通过U盘启动就可以识别到ISO镜像开始装系统

MySQL 日志管理、备份与恢复

一、MySQL 日志管理 MySQL 的日志默认保存位置为 /usr/local/mysql/data vim /etc/my.cnf [mysqld] ##错误日志&#xff0c;用来记录当MySQL启动、停止或运行时发生的错误信息&#xff0c;默认已开启 log-error/usr/local/mysql/data/mysql_error.log #指定日志的保存位置…

springboot项目基于jdk17、分布式事务seata-server-1.7.1、分库分表shardingSphere5.2.1开发过程中出现的问题

由于项目需要&#xff0c;springboot项目需基于jdk17环境开发&#xff0c;结合nacos2.0.3、分布式事务seata-server-1.7.1、分库分表shardingSphere5.2.1等&#xff0c;项目启动过程中出现的问题解决方式小结。 问题一&#xff1a; Caused by: java.lang.RuntimeException: j…

职场Excel:求和家族,不简单

说到excel函数&#xff0c;很多人第一时间想到的就是求和函数sum。作为excel入门级函数&#xff0c;sum的确是小白级的&#xff0c;以至于很多人对求和函数有点“误解”&#xff0c;觉得求和函数太简单了。 但是&#xff0c;你可能不知道&#xff0c;sum只是excel求和家族里的一…

Ubuntu22.04 交叉编译GCC13.2.0 for Rv1126

一、安装Ubuntu22.04 sudo apt install vim net-tools openssh-server 二、安装必要项 sudo apt update sudo apt upgrade sudo apt install build-essential gawk git texinfo bison flex 三、下载必备软件包 1.glibc https://ftp.gnu.org/gnu/glibc/glibc-2.38.tar.gz…

引迈-JNPF低代码项目技术栈介绍

从 2014 开始研发低代码前端渲染&#xff0c;到 2018 年开始研发后端低代码数据模型&#xff0c;发布了JNPF开发平台。 谨以此文针对 JNPF-JAVA-Cloud微服务 进行相关技术栈展示&#xff1a; 1. 项目前后端分离 前端采用Vue.js&#xff0c;这是一种流行的前端JavaScript框架&a…

4D毫米波雷达和3D雷达、激光雷达全面对比

众所周知&#xff0c;传统3D毫米波雷达存在如下性能缺陷&#xff1a; 1&#xff09;静止目标和地物杂波混在一起&#xff0c;难以区分&#xff1b; 2) 横穿车辆和行人多普勒为零或很低&#xff0c;难以检测&#xff1b; 3) 高处物体和地面目标不能区分&#xff0c;容易造成误刹…

从CNN到Transformer:基于PyTorch的遥感影像、无人机影像的地物分类、目标检测、语义分割和点云分类

我国高分辨率对地观测系统重大专项已全面启动&#xff0c;高空间、高光谱、高时间分辨率和宽地面覆盖于一体的全球天空地一体化立体对地观测网逐步形成&#xff0c;将成为保障国家安全的基础性和战略性资源。随着小卫星星座的普及&#xff0c;对地观测已具备多次以上的全球覆盖…

部署单仓库多目录项目

部署单仓库多目录项目 文章目录 部署单仓库多目录项目1.部署单仓库多目录项目2.Shell脚本进行部署单仓库多目录项目2.1 编写Shell脚本2.2 Demo推送代码及测试 3.小结 1.部署单仓库多目录项目 #部署单仓库多目录项目 在开发过程中,研发团队往往会将一个大型项目拆分成几个子目录…

MCU 的 TOP 15 图形GUI库:选择最适合你的图形用户界面(一)

在嵌入式系统开发中&#xff0c;选择一个合适的图形用户界面&#xff08;GUI&#xff09;库是至关重要的。在屏幕上显示的时候&#xff0c;使用现成的图形库&#xff0c;这样开发人员就不需要弄清楚底层任务&#xff0c;例如如何绘制像素、线条、形状&#xff0c;如果再高级一点…

基于骑手优化算法优化概率神经网络PNN的分类预测 - 附代码

基于骑手优化算法优化概率神经网络PNN的分类预测 - 附代码 文章目录 基于骑手优化算法优化概率神经网络PNN的分类预测 - 附代码1.PNN网络概述2.变压器故障诊街系统相关背景2.1 模型建立 3.基于骑手优化优化的PNN网络5.测试结果6.参考文献7.Matlab代码 摘要&#xff1a;针对PNN神…

2021秋招-总目录

2021秋招-目录 知识点总结 预训练语言模型: Bert家族 1.1 BERT、attention、transformer理解部分 B站讲解–强烈推荐可视化推倒结合代码理解代码部分常见面试考点以及问题: word2vec 、 fasttext 、elmo;BN 、LN、CN、WNNLP中的loss与评价总结 4.1 loss_function&#xff1…

基于AVR单片机的移动目标视觉追踪系统设计与实现

基于AVR单片机的移动目标视觉追踪系统是一种常见的应用领域&#xff0c;旨在通过摄像头采集图像数据并使用图像处理和追踪算法实现对移动目标的实时追踪。本文将介绍基于AVR单片机的移动目标视觉追踪系统的设计原理和实现步骤&#xff0c;并提供相应的代码示例。 1. 设计概述 …

基于SSM的校内互助交易平台设计

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;Vue 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#xff1a;是 目录…

MAX/MSP SDK学习04:Messages selector的使用

其实消息选择器在simplemax示例中就接触到了&#xff0c;但这文档非要讲那么抽象。目前为止对消息选择器的理解是&#xff1a;可判断接收过来的消息是否符合本Object的处理要求&#xff0c;比如加法对象只可接收数值型的消息以处理&#xff0c;但不能接收t_symbol型的消息&…

【Spring Boot】如何在Linux系统中快速启动Spring Boot的jar包

在Linux系统中先安装java的JDK 然后编写下列service.sh脚本&#xff0c;并根据自己的需求只需要修改export的log_path、exec_cmd参数即可 # 配置运行日志输出的路径 export log_path/usr/local/project/study-pro/logs # 当前服务运行的脚本命令 export exec_cmd"nohup /u…