您现在的位置是:首页 >技术教程 >UE5.1.1C++从0开始(7.增加人物血量属性)网站首页技术教程

UE5.1.1C++从0开始(7.增加人物血量属性)

楚江_wog1st 2024-06-17 10:31:52
简介UE5.1.1C++从0开始(7.增加人物血量属性)

说句实话这一节有点坑,教程上老师的那个项目其实是没有向我写的这些代码一样,做一个父类,然后写三个子类的子弹的,所以老师的代码只需要更改一点点东西就好,而我们的代码可能需要考虑的东西就比较多。

好了,首先还是,为了避免我们的人物的代码过多,同时方便我们将这些可复用的代码复用到别的地方,我们需要像之前创建互动组件那样,再创建一个属性组件(SAttributeComponent)

老师在这一节课讲了他前几节课都没讲的点:UPROPERTY的宏内的属性到底都是些什么意思?有什么用?我这里加上了点个人的思考,然后翻译成了中文放出来,看不懂的可以参考我的这个翻译版本

/**
 * EditAnywhere -- 在蓝图编辑器以及每一个层级的实例内都可以修改
 * VisibleAnywhere -- ‘只读’于编辑器和每个层级
 * EditDefaultsOnly -- 在每个实例中都隐藏变量,只能在蓝图编辑器内修改
 * VisibleDefaultsOnly -- 对于实例来说,所有的变量都是‘只读’的
 * EditInstanceOnly -- 只允许编辑实例
 * BluePrintReadOnly -- 对于蓝图编辑器来说,是只读的(不影响细节面板)
 * BluePrintReadWrite -- 基于蓝图编辑器‘读写’的操作权限
 */

还是按照惯例,我在写这些代码的时候并没有遇到什么太大的困难,所以直接放代码

SAttributeComponent.h

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

#pragma once

#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "SAttributeComponent.generated.h"


UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class ACTIONROGUELIKE_API USAttributeComponent : public UActorComponent
{
	GENERATED_BODY()

protected:
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Attributes")
	float Health;

public:	
	// Sets default values for this component's properties
	USAttributeComponent();

public:	

	UFUNCTION(BlueprintCallable,Category="Attributes")
	bool ApplyHealthChange(float Delta);
	
};

SAttributeComponent.cpp

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


#include "SAttributeComponent.h"

// Sets default values for this component's properties
USAttributeComponent::USAttributeComponent()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
    //我这里没有删这一行代码,是因为我不确定父类的默认值是多少,老师说不需要,只是为了看上去很简洁,我想了下,一些基本设置还是留下,不删了,函数什么时候都能加回来的,属性我比较懒,以后有什么需要直接改好了,就不用再去找有啥属性了
	PrimaryComponentTick.bCanEverTick = true;

	// ...
	Health = 100.0f;
}

bool USAttributeComponent::ApplyHealthChange(float Delta)
{
	Health += Delta;
	return true;
}


接下来就是一个让我感觉很坑爹的地方,老师那里的扣血功能的实现,他只是在他做的一个单一的类中,而我们的代码是自己写了一个父类和多个子类的,那么我们的增加的新功能要放到哪里呢?我思考了下,决定放到父类组件内,一些功能性的子弹在子类里面再更改扣的血量就好了。需要注意的点还是用中文打了注释,自己看,看不明白问我

SFatherMagicProjectile.h

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

#pragma once

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

UCLASS()
class ACTIONROGUELIKE_API ASFatherMagicProjectile : public AActor
{
	GENERATED_BODY()

public:
	UPROPERTY(EditAnywhere)
	class USphereComponent * SphereComp;

	UPROPERTY(EditAnywhere)
	class UProjectileMovementComponent * MovementComp;

	UPROPERTY(EditAnywhere)
	class UParticleSystemComponent * ParticleComp;
	
public:	
	// Sets default values for this actor's properties
	ASFatherMagicProjectile();

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

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	UFUNCTION()
	virtual void OnComponentHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, FHitResult Hit);
	
    //新加的函数
	UFUNCTION()
	void OnComponentOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
};

SFatherMagicProjectile.cpp

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


#include "SFatherMagicProjectile.h"
#include "Components/SphereComponent.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "Particles/ParticleSystemComponent.h"
#include "SAttributeComponent.h"

// Sets default values
ASFatherMagicProjectile::ASFatherMagicProjectile()
{
 	// 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;

	FScriptDelegate OnHit;
	OnHit.BindUFunction(this, STATIC_FUNCTION_FNAME(TEXT("ASFatherMagicProjectile::OnComponentHit")));
	
    //写一个委托,还记得第一个作业么?我们就是这么实现的C++绑定函数
    FScriptDelegate OnOverlap;
	OnOverlap.BindUFunction(this, STATIC_FUNCTION_FNAME(TEXT("ASFatherMagicProjectile::OnComponentOverlap")));

	SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere Comp"));
	SphereComp->SetCollisionProfileName("Projectile");
	SphereComp->SetSphereRadius(10.0f, true);
	SphereComp->OnComponentHit.Add(OnHit);
    //增加事件绑定函数,教程的老师使用的是AddDelegate(),其实两个实现方法并无本质上的区别,看各位喜好,我这里提供另一种方法罢了
	SphereComp->OnComponentBeginOverlap.Add(OnOverlap);
	RootComponent = SphereComp;

	MovementComp = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("Movement Comp"));
	MovementComp->InitialSpeed = 1000.0f;
	MovementComp->bRotationFollowsVelocity = true;
	MovementComp->bInitialVelocityInLocalSpace = true;
	MovementComp->ProjectileGravityScale = 0.0f;

	ParticleComp = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("Particle Comp"));
	ParticleComp->SetupAttachment(SphereComp);

}

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

	APawn* Instigator_01 = AActor::GetInstigator();

	SphereComp->IgnoreActorWhenMoving(Instigator_01, true);

}

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

}

void ASFatherMagicProjectile::OnComponentHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, FHitResult Hit)
{
	APawn* Instigator_01 = AActor::GetInstigator();

	if (Instigator_01!=OtherActor)
	{
		GetWorld()->DestroyActor(this);
		DrawDebugSphere(GetWorld(), Hit.ImpactPoint, 10.0f, 16, FColor::Red, false, 2.0f, 0U, 1.0f);
	}
}
//我们的重叠函数,我在删除自身的地方又加了一个判断,判断是否是自身,这相当于一个保险吧,教程没加看着也没啥问题,不过我没有自己去确定,于是加了一层判断
void ASFatherMagicProjectile::OnComponentOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	APawn* Instigator_01 = AActor::GetInstigator();

	if (OtherActor)
	{
		USAttributeComponent* AttributeComp = Cast<USAttributeComponent>(OtherActor->GetComponentByClass(USAttributeComponent::StaticClass()));
		if (AttributeComp)
		{
			AttributeComp->ApplyHealthChange(-20.0f);
			if (Instigator_01 != OtherActor)
			{
				GetWorld()->DestroyActor(this);
			}
		}

	}
}

SCharacter文件并没有做大修改,只是把这个组件附加到了自身身上并实例化了而已

SCharacter.h

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

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h"
#include "SCharacter.generated.h"




UCLASS(config = Game)
class ACTIONROGUELIKE_API ASCharacter : public ACharacter
{
	GENERATED_BODY()

	UPROPERTY(VisibleAnywhere)
	class USpringArmComponent* SpringArmComp;

	UPROPERTY(VisibleAnywhere)
	class UCameraComponent* CameraComp;

    //增加的属性组件
public:
	UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category="Components")
	class USAttributeComponent* AttributeComp;

	UPROPERTY(EditAnywhere, Category = Input)
	class UInputMappingContext* DefaultMappingContext;

	UPROPERTY(EditAnywhere,  Category = Input)
	class UInputAction* MoveAction;

	UPROPERTY(EditAnywhere,  Category = Input)
	class UInputAction* JumpAction;

	UPROPERTY(EditAnywhere, Category = Input)
	class UInputAction* LookAction;

	UPROPERTY(EditAnywhere, Category = Input)
	class UInputAction* PrimaryAttackAction;

	UPROPERTY(EditAnywhere, Category = Input)
	class UInputAction* InteractionAction;

	UPROPERTY(VisibleAnywhere)
	class USInteractionComponent* InteractionComp;

	
	
protected:
	UPROPERTY(EditAnywhere)
	class TSubclassOf<AActor> ProjectileClass;

public:
	// Sets default values for this character's properties
	ASCharacter();

protected:

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

protected:
	void Move(const FInputActionValue& Value);

	void Look(const FInputActionValue& Value);

	void PrimaryAttack();

	void PrimaryInteract();

	void PrimaryAttack_TimeElasped();

protected:
	FTimerHandle TimerHandle_PrimaryAttack;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	// Called to bind functionality to input
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

};

SCharacter.cpp

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


#include "SCharacter.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/Controller.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "SInteractionComponent.h"
#include "TimerManager.h"
#include "SAttributeComponent.h"
//#include "../../../../../UE_5.1/Engine/Plugins/EnhancedInput/Source/EnhancedInput/Public/EnhancedInputSubsystems.h"
//#include "../../../../../UE_5.1/Engine/Plugins/EnhancedInput/Source/EnhancedInput/Public/EnhancedInputComponent.h"


// Sets default values
ASCharacter::ASCharacter()
{
 	// 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;

	bUseControllerRotationPitch = false;
	bUseControllerRotationRoll = false;
	bUseControllerRotationYaw = false;

	GetCharacterMovement()->bOrientRotationToMovement = true;

	SpringArmComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
	SpringArmComp->SetupAttachment(RootComponent);
	SpringArmComp->bUsePawnControlRotation = true;

	CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
	CameraComp->SetupAttachment(SpringArmComp);
	CameraComp->bUsePawnControlRotation = false;
	//实例化组件
	AttributeComp = CreateDefaultSubobject<USAttributeComponent>(TEXT("Attribute Comp"));

	InteractionComp = CreateDefaultSubobject<USInteractionComponent>(TEXT("InteractionComp"));

}

// Called when the game starts or when spawned
void ASCharacter::BeginPlay()
{
	Super::BeginPlay();
	if (APlayerController* PlayerController = Cast<APlayerController>(Controller))
	{
		if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer()))
		{
			Subsystem->AddMappingContext(DefaultMappingContext, 0);
		}
	}

	
}

void ASCharacter::Move(const FInputActionValue& Value)
{
	FVector2D MovementVector = Value.Get<FVector2D>();

	if (Controller!=nullptr)
	{
		const FRotator Rotation = Controller->GetControlRotation();
		//拿到控制器的Yaw面的旋转角度,而不是Character的旋转角度
		const FRotator YawRotation(0, Rotation.Yaw, 0);

		//把角度用向量来表示,同时获取到不同方向的向量值,而这个向量的角度是按照我们控制器的角度来说的
		const FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		const FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
		
		//MovementVector的X和Y是相对于我们的视角来说的,也就是我们视角的正前方是Y,而我们视角的正右方是X
		AddMovementInput(ForwardDirection, MovementVector.Y);
		AddMovementInput(RightDirection, MovementVector.X);
	}
}

void ASCharacter::Look(const FInputActionValue& Value)
{
	FVector2D LookAxisVector = Value.Get<FVector2D>();

	if (Controller!=nullptr)
	{
		AddControllerYawInput(LookAxisVector.X);
		AddControllerPitchInput(LookAxisVector.Y);
	}
}

void ASCharacter::PrimaryAttack()
{

	GetWorldTimerManager().SetTimer(TimerHandle_PrimaryAttack,this,&ASCharacter::PrimaryAttack_TimeElasped,0.2f);

	
}

void ASCharacter::PrimaryInteract()
{
	if (InteractionComp)
	{
		InteractionComp->PrimaryInteract();
	}	
}

void ASCharacter::PrimaryAttack_TimeElasped()
{
	//人物起始位置
	FVector StartPoint;
	//视角起始位置
	FVector StartPoint_Camera = CameraComp->GetComponentLocation();
	//增加的旋转
	FRotator EyeRotation;
	GetActorEyesViewPoint(StartPoint, EyeRotation);
	StartPoint = GetActorLocation();
	//终点位置
	FVector EndPoint = StartPoint_Camera+(EyeRotation.Vector()*10000.0f);
	//碰撞结果
	FHitResult HitResult;
	//配置属性
	FCollisionObjectQueryParams ObjectQueryParams;
	ObjectQueryParams.AddObjectTypesToQuery(ECC_WorldStatic);
	//判断是否有碰撞
	bool bBlockingHit = GetWorld()->LineTraceSingleByObjectType(HitResult,StartPoint_Camera,EndPoint,ObjectQueryParams);
	//旋转
	FRotator StartRotation = EyeRotation;
	//没有碰撞的话,我们将最远端的指向位置设为目标点
	DrawDebugLine(GetWorld(), StartPoint_Camera, EndPoint, FColor::Red, false, 2.0f, 0U, 1.0f);
	if (bBlockingHit)
	{
		//终点减去起点
		StartRotation = (HitResult.ImpactPoint - StartPoint).Rotation();
		FString HitPoint = FString::Printf(TEXT("EndPoint:%s, Rotation:%s"), *HitResult.ImpactPoint.ToString(), *StartRotation.ToString());

		DrawDebugString(GetWorld(), HitResult.ImpactPoint, HitPoint, nullptr, FColor::Red, 2.0f, true, 1.0f);
		DrawDebugLine(GetWorld(), StartPoint, HitResult.ImpactPoint, FColor::Green, false, 2.0f, 0U, 1.0f);
	}
	else
	{
		StartRotation = (EndPoint - StartPoint).Rotation();
		DrawDebugLine(GetWorld(), StartPoint, EndPoint, FColor::Green, false, 2.0f, 0U, 1.0f);
	}


	FTransform SpawnTM = FTransform(StartRotation, StartPoint);
	FActorSpawnParameters SpawnParams;
	//生成参数的碰撞覆盖处理,是尽可能不和自己有重叠呢,还是说不论三七二十一就是生成对象
	//ISSUE:生成的子弹队人物会造成碰撞导致人物强行位移
	SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
	SpawnParams.Instigator = this;

	AActor* MagicProjectile = GetWorld()->SpawnActor < AActor >(ProjectileClass, SpawnTM, SpawnParams);
	
}

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

}

// Called to bind functionality to input
void ASCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	if (UEnhancedInputComponent* EnhancedInputComponent = CastChecked<UEnhancedInputComponent>(PlayerInputComponent))
	{
		//MoveAction
		EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &ASCharacter::Move);

		//JumpAction
		EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Triggered, this, &ACharacter::Jump);
		EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Completed, this, &ACharacter::StopJumping);

		//LookAction
		EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &ASCharacter::Look);

		//PrimaryAttack
		EnhancedInputComponent->BindAction(PrimaryAttackAction, ETriggerEvent::Triggered, this, &ASCharacter::PrimaryAttack);

		//Interaction
		EnhancedInputComponent->BindAction(InteractionAction, ETriggerEvent::Triggered, this, &ASCharacter::PrimaryInteract);
	}

}


风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。