首页 > 其他分享 >UE5学习笔记9-创建一个小窗口提示人物是否和武器重叠

UE5学习笔记9-创建一个小窗口提示人物是否和武器重叠

时间:2024-08-12 19:27:46浏览次数:15  
标签:重叠 AWeapon void 碰撞 笔记 AreaSphere 设置 UE5 include

一、目标

        创建一个UsrWidget去显示如果人物和武器重叠显示窗口,如果人物和武器不重叠将窗口隐藏

二、创建窗口并显示

        1.创建一个窗口蓝图类,命名为PickUpWidget,这个蓝图类不需要C++类,在对应文件夹中单机右键选择用户界面的控件蓝图

        2.在界面蓝图类中添加一个text控件,将字体设置为front,居中显示,可以在右侧栏找到对应设置,将控件命名为PickUpText

         3.在之前创建的武器的C++类中绑定text控件 ,在头文件中声明一个界面组件的指针在cpp文件中的构造函数中初始化这个指针

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

#pragma once

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

// 一个枚举类 作为蓝图的类型
UENUM(BlueprintType) /* 可以将此枚举用作蓝图中的一种类型 */
enum class EWeaponState : uint8
{
	EWS_Initial UMETA(DisplayName = "Initial State"),
	EWS_Equipped UMETA(DisplayName = "Equipped"),
	EWS_Dropped UMETA(DisplayName = "Dropped"),

	EWS_MAX UMETA(DisplayName = "DefaultMAX")
};

UCLASS()
class BLASTER_API AWeapon : public AActor
{
	GENERATED_BODY()

public:
	// Sets default values for this actor's properties
	AWeapon();
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	/** 设置何时显示提示框 是否角色和武器重叠 */
	void ShowPickupWidget(bool bShowWidget);
protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:


private:
	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties") // 设置在任何地方都可以看见,类别设置为武器属性
	USkeletalMeshComponent* WeapomMesh;	/* 骨骼网格 */
	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	class USphereComponent* AreaSphere; /* 球形组件 判断人物模型和武器模型是否重叠 */

	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	EWeaponState WeaponState;

	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	class UWidgetComponent* PickWidget; /* 界面组件 */
};
// Fill out your copyright notice in the Description page of Project Settings.


#include "Weapon.h"
#include "Components/SphereComponent.h"
#include "Components/WidgetComponent.h"
#include "Net/UnrealNetwork.h"
#include "Blaster/Character/BlasterCharacter.h"

// Sets default values
AWeapon::AWeapon()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;
	bReplicates = true; //将执行组件复制到远程计算机 //由于想要将武器在服务器上判断是否碰撞,需要将武器作为一个actor复制到服务器上

	WeapomMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("WeaponMesh")); //创建骨骼网格提成员,名字是WeaponMesh
	//WeapomMesh->SetupAttachment(RootComponent); //一个组件附加到另一个组件上
	SetRootComponent(WeapomMesh);//设置根组件

	// 当拿起武器时设置为完全阻止SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Block)
	// 当丢掉武器时设置为设置为忽略,即没有碰撞SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Ignore)
	// 当武器在地上时设置无碰撞SetCollisionEnabled(ECollisionEnabled::NoCollision) 
	WeapomMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Block); //将碰撞响应设置为完全阻止
	WeapomMesh->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Ignore);//当放下武器时将任务设置为忽略,即没有碰撞
	WeapomMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);//设置无碰撞 

	// 想在服务器上检测当前碰撞区域是否和角色重叠
	// 将碰撞区域设置为SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore)不要碰撞
	// 设置为在所有机上都是无碰撞SetCollisionEnabled(ECollisionEnabled::NoCollision); 
	// 在服务器上设置为启用碰撞 不在构造函数中设置,在游戏开始时BeginPlay()设置
	AreaSphere = CreateDefaultSubobject<USphereComponent>(TEXT("AreaSphere"));
	AreaSphere->SetupAttachment(RootComponent);
	AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);
	AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);

	PickWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("PickUpWidget"));
	PickWidget->SetupAttachment(RootComponent);
}

void AWeapon::ShowPickupWidget(bool bShowWidget)
{
	if (PickWidget)
	{
		PickWidget->SetVisibility(bShowWidget);
	}
}

// Called when the game starts or when spawned
void AWeapon::BeginPlay()
{
	Super::BeginPlay();
	
	// (GetLocalRole() == ENetRole::ROLE_Authority) == HasAuthority()	作用相同
	//	GetLocalRole() 获得本地角色 ENetRole::ROLE_Authority 是否具有角色权威
	if ( HasAuthority() )
	{ 
		//如果当前是在服务器上,将碰撞设置为查询物理碰撞
		AreaSphere->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
		//设置当前的碰撞是胶囊碰撞ECC_Pawn,并将碰撞设置为重叠ECR_Overlap
		AreaSphere->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn,ECollisionResponse::ECR_Overlap);
	}
}

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

}

         4.编译代码,打开武器的蓝图类可以在左侧栏看见刚添加的组件,选中当前组件在右侧谢绝栏中的用户界面下拉框中将空间改成屏幕,将空间类选择成刚才创建的pickupwidget的蓝图类的名字,将以所需大小绘制勾选,最后将提示框放到你想放到的位置上,如图。

        5.显示完成可以运行查看,若没有按照正确的位置显示请查看武器类的构造函数中这两行代码是否有设置跟组件,请将武器的骨骼设置为跟组件将另一行代码注释或删除

        WeapomMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("WeaponMesh")); //创建骨骼网格提成员,名字是WeaponMesh
    //WeapomMesh->SetupAttachment(RootComponent); //一个组件附加到另一个组件上
    SetRootComponent(WeapomMesh);//设置根组件 

三、创建一个重叠部分判断的功能

        1.在头文件中添加一个函数用来判断是否发生重叠

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

#pragma once

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

// 一个枚举类 作为蓝图的类型
UENUM(BlueprintType) /* 可以将此枚举用作蓝图中的一种类型 */
enum class EWeaponState : uint8
{
	EWS_Initial UMETA(DisplayName = "Initial State"),
	EWS_Equipped UMETA(DisplayName = "Equipped"),
	EWS_Dropped UMETA(DisplayName = "Dropped"),

	EWS_MAX UMETA(DisplayName = "DefaultMAX")
};

UCLASS()
class BLASTER_API AWeapon : public AActor
{
	GENERATED_BODY()

public:
	// Sets default values for this actor's properties
	AWeapon();
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	/** 设置何时显示提示框 是否角色和武器重叠 */
	void ShowPickupWidget(bool bShowWidget);
protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	UFUNCTION()
	virtual void OnSphereOverlap(
		UPrimitiveComponent* OverlappedComponent,// UPrimitiveComponent重叠组件类
		AActor* OtherActor,
		UPrimitiveComponent* OtherComp,
		int32 OtherBodyIndex,
		bool bFromSweep,
		const FHitResult& SweepResult	//碰撞检测结果
	);

public:


private:
	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties") // 设置在任何地方都可以看见,类别设置为武器属性
	USkeletalMeshComponent* WeapomMesh;	/* 骨骼网格 */
	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	class USphereComponent* AreaSphere; /* 球形组件 判断人物模型和武器模型是否重叠 */

	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	EWeaponState WeaponState;

	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	class UWidgetComponent* PickWidget; /* 界面组件 */
};
// Fill out your copyright notice in the Description page of Project Settings.


#include "Weapon.h"
#include "Components/SphereComponent.h"
#include "Components/WidgetComponent.h"
#include "Net/UnrealNetwork.h"
#include "Blaster/Character/BlasterCharacter.h"

// Sets default values
AWeapon::AWeapon()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;
	bReplicates = true; //将执行组件复制到远程计算机 //由于想要将武器在服务器上判断是否碰撞,需要将武器作为一个actor复制到服务器上

	WeapomMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("WeaponMesh")); //创建骨骼网格提成员,名字是WeaponMesh
	//WeapomMesh->SetupAttachment(RootComponent); //一个组件附加到另一个组件上
	SetRootComponent(WeapomMesh);//设置根组件

	// 当拿起武器时设置为完全阻止SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Block)
	// 当丢掉武器时设置为设置为忽略,即没有碰撞SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Ignore)
	// 当武器在地上时设置无碰撞SetCollisionEnabled(ECollisionEnabled::NoCollision) 
	WeapomMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Block); //将碰撞响应设置为完全阻止
	WeapomMesh->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Ignore);//当放下武器时将任务设置为忽略,即没有碰撞
	WeapomMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);//设置无碰撞 

	// 想在服务器上检测当前碰撞区域是否和角色重叠
	// 将碰撞区域设置为SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore)不要碰撞
	// 设置为在所有机上都是无碰撞SetCollisionEnabled(ECollisionEnabled::NoCollision); 
	// 在服务器上设置为启用碰撞 不在构造函数中设置,在游戏开始时BeginPlay()设置
	AreaSphere = CreateDefaultSubobject<USphereComponent>(TEXT("AreaSphere"));
	AreaSphere->SetupAttachment(RootComponent);
	AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);
	AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);

	PickWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("PickUpWidget"));
	PickWidget->SetupAttachment(RootComponent);
}

void AWeapon::ShowPickupWidget(bool bShowWidget)
{
	if (PickWidget)
	{
		PickWidget->SetVisibility(bShowWidget);
	}
}

// Called when the game starts or when spawned
void AWeapon::BeginPlay()
{
	Super::BeginPlay();
	
	// (GetLocalRole() == ENetRole::ROLE_Authority) == HasAuthority()	作用相同
	//	GetLocalRole() 获得本地角色 ENetRole::ROLE_Authority 是否具有角色权威
	if ( HasAuthority() )
	{ 
		//如果当前是在服务器上,将碰撞设置为查询物理碰撞
		AreaSphere->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
		//设置当前的碰撞是胶囊碰撞ECC_Pawn,并将碰撞设置为重叠ECR_Overlap
		AreaSphere->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn,ECollisionResponse::ECR_Overlap);
    }
    if (PickWidget)
    {
	    PickWidget->SetVisibility(false);
    }
}

void AWeapon::OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	ABlasterCharacter* BlasterCharacter = Cast<ABlasterCharacter>(OtherActor);
	if (BlasterCharacter && PickWidget )
	{
		PickWidget->SetVisibility(true);
	}
}


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

}

四、当前效果

        在服务器上发生重叠可以看见提示,在客户端中看不见,当客户端发生重叠时客户端看不见提示在服务器上可以看见

五、创建一个当结束重叠时将提示款设置不可见

        一点说明:定义一个函数OnSphereEndOverlap代表结束重叠将会去实现的功能,在beginplay函数中通过之前定义的class USphereComponent* AreaSphere;指针调用OnComponentBeginOverlap 去绑定重叠开始的函数,调用OnComponentEndOverlap去绑定重叠结束的函数,参数可以在OnComponentBeginOverlap/OnComponentEndOverlap通过F12转到定义去查看。

        定义中FComponentBeginOverlapSignature OnComponentBeginOverlap;对FComponentBeginOverlapSignature转定义DECLARE_DYNAMIC_MULTICAST_SPARSE_DELEGATE_SixParams( FComponentBeginOverlapSignature, UPrimitiveComponent, OnComponentBeginOverlap, UPrimitiveComponent*, OverlappedComponent, AActor*, OtherActor, UPrimitiveComponent*, OtherComp, int32, OtherBodyIndex, bool, bFromSweep, const FHitResult &, SweepResult);可以看见是一个宏函数有10个参数(为啥我有7个现在我也没整明白,视频中是这么写的,之后在研究)

        xxx.h

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

#pragma once

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

// 一个枚举类 作为蓝图的类型
UENUM(BlueprintType) /* 可以将此枚举用作蓝图中的一种类型 */
enum class EWeaponState : uint8
{
	EWS_Initial UMETA(DisplayName = "Initial State"),
	EWS_Equipped UMETA(DisplayName = "Equipped"),
	EWS_Dropped UMETA(DisplayName = "Dropped"),

	EWS_MAX UMETA(DisplayName = "DefaultMAX")
};

UCLASS()
class BLASTER_API AWeapon : public AActor
{
	GENERATED_BODY()

public:
	// Sets default values for this actor's properties
	AWeapon();
	// Called every frame
	virtual void Tick(float DeltaTime) override;
    /** 要标记要复制的内容,我们使用 UPROPERTY 中的 Replicated 说明符。
    在将某个内容标记为 Replicated 之后,我们必须定义一个名为 GetLifetimeReplicatedProps 的新            
    函数 */
    /** 返回用于网络复制的属性,这需要被所有具有本机复制属性的 actor 类覆盖 */
	virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
	/** 设置何时显示提示框 是否角色和武器重叠 */
	void ShowPickupWidget(bool bShowWidget);
protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	UFUNCTION()
	virtual void OnSphereOverlap(
		UPrimitiveComponent* OverlappedComponent,// UPrimitiveComponent重叠组件类
		AActor* OtherActor,
		UPrimitiveComponent* OtherComp,
		int32 OtherBodyIndex,
		bool bFromSweep,
		const FHitResult& SweepResult	//碰撞检测结果
	);

	/** 重叠结束 */
	UFUNCTION()
	virtual void OnSphereEndOverlap(
		UPrimitiveComponent* OverlappedComponent,// UPrimitiveComponent重叠组件类
		AActor* OtherActor,
		UPrimitiveComponent* OtherComp,
		int32 OtherBodyIndex
	);

private:
	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties") // 设置在任何地方都可以看见,类别设置为武器属性
	USkeletalMeshComponent* WeapomMesh;	/* 骨骼网格 */
	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	class USphereComponent* AreaSphere; /* 球形组件 判断人物模型和武器模型是否重叠 */

	UPROPERTY(ReplicatedUsing = OnRep_WeaponState, VisibleAnywhere, Category = "Weapon Properties")
	EWeaponState WeaponState;

	UFUNCTION()
	void OnRep_WeaponState();

	UPROPERTY(VisibleAnywhere, Category = "Weapon Properties")
	class UWidgetComponent* PickWidget; /* 界面组件 */

public:
	void SetWeaponState(EWeaponState state);
};

        xxx.cpp

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


#include "Weapon.h"
#include "Components/SphereComponent.h"
#include "Components/WidgetComponent.h"
#include "Net/UnrealNetwork.h"
#include "Blaster/Character/BlasterCharacter.h"

// Sets default values
AWeapon::AWeapon()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;
	bReplicates = true; //将执行组件复制到远程计算机 //由于想要将武器在服务器上判断是否碰撞,需要将武器作为一个actor复制到服务器上

	WeapomMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("WeaponMesh")); //创建骨骼网格提成员,名字是WeaponMesh
	//WeapomMesh->SetupAttachment(RootComponent); //一个组件附加到另一个组件上
	SetRootComponent(WeapomMesh);//设置根组件

	// 当拿起武器时设置为完全阻止SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Block)
	// 当丢掉武器时设置为设置为忽略,即没有碰撞SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Ignore)
	// 当武器在地上时设置无碰撞SetCollisionEnabled(ECollisionEnabled::NoCollision) 
	WeapomMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Block); //将碰撞响应设置为完全阻止
	WeapomMesh->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Ignore);//当放下武器时将任务设置为忽略,即没有碰撞
	WeapomMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);//设置无碰撞 

	// 想在服务器上检测当前碰撞区域是否和角色重叠
	// 将碰撞区域设置为SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore)不要碰撞
	// 设置为在所有机上都是无碰撞SetCollisionEnabled(ECollisionEnabled::NoCollision); 
	// 在服务器上设置为启用碰撞 不在构造函数中设置,在游戏开始时BeginPlay()设置
	AreaSphere = CreateDefaultSubobject<USphereComponent>(TEXT("AreaSphere"));
	AreaSphere->SetupAttachment(RootComponent);
	AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);
	AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);

	PickWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("PickUpWidget"));
	PickWidget->SetupAttachment(RootComponent);
}

void AWeapon::ShowPickupWidget(bool bShowWidget)
{
	if (PickWidget)
	{
		PickWidget->SetVisibility(bShowWidget);
	}
}

// Called when the game starts or when spawned
void AWeapon::BeginPlay()
{
	Super::BeginPlay();
	
	// (GetLocalRole() == ENetRole::ROLE_Authority) == HasAuthority()	作用相同
	//	GetLocalRole() 获得本地角色 ENetRole::ROLE_Authority 是否具有角色权威
	if ( HasAuthority() )
	{ 
		//如果当前是在服务器上,将碰撞设置为物理碰撞
		AreaSphere->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
		//设置当前的碰撞是胶囊碰撞ECC_Pawn,并将碰撞设置为重叠ECR_Overlap
		AreaSphere->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn,ECollisionResponse::ECR_Overlap);
		// 绑定一个重叠区域处理函数
		AreaSphere->OnComponentBeginOverlap.AddDynamic(this,&AWeapon::OnSphereOverlap);
		AreaSphere->OnComponentEndOverlap.AddDynamic(this, &AWeapon::OnSphereEndOverlap);
	}

	if (PickWidget)
	{
		PickWidget->SetVisibility(false);
	}
}

void AWeapon::OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	ABlasterCharacter* BlasterCharacter = Cast<ABlasterCharacter>(OtherActor);
	if (BlasterCharacter /* && PickWidget */ )
	{
		//PickWidget->SetVisibility(true);
		BlasterCharacter->SetOverlappingWeapon(this);
	}
}

void AWeapon::OnSphereEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
	ABlasterCharacter* BlasterCharacter = Cast<ABlasterCharacter>(OtherActor);
	if (BlasterCharacter /* && PickWidget */)
	{
		//PickWidget->SetVisibility(true);
		BlasterCharacter->SetOverlappingWeapon(nullptr);
	}
}

void AWeapon::OnRep_WeaponState()
{
	switch (WeaponState)
	{
	case EWeaponState::EWS_Equipped:
		ShowPickupWidget(false);
		//AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);
		break;
	}
}

void AWeapon::SetWeaponState(EWeaponState state)
{
	WeaponState = state;
	switch (WeaponState)
	{
	case EWeaponState::EWS_Equipped:
		ShowPickupWidget(false);
		AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);
		break;
	}
	
}

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

}

        六、当前的问题

        可能会有测试游戏时在服务器上人物与武器重叠时会有提示框不会在客户端显示,重新测试当客户端与武器重叠时当前客户端和服务器上都会有提示,这是因为在重叠时武器的状态会改变,之前在人物的C++类中定义的武器的变量存在服务器一份客户端一份,客户端的武器变量改变时服务器也会发生改变,可以在人物C++中加判断

        七、人物C++类代码

        1.说明

        在头文件中添加了武器类的指针和当状态改变时的回调函数同时重写GetLifetimeReplicatedProps函数指定复制变量的类和复制的变量,同时设置了指定的条件

        2.ReplicatedUsing = OnReq_XX:作用是绑定了OnReq_XX回调函数,在当前变量改变时调用,也说明当前变量是一个可复制的变量

        3.DOREPLIFETIME_CONDITION的作用是:/** 指定了具有复制变量的类 和 复制的变量是哪个 , 复制的条件是什么  */DOREPLIFETIME_CONDITION(ABlasterCharacter, OverLappingWeapon, COND_OwnerOnly);若是DOREPLIFETIME宏则只有(ABlasterCharacter, OverLappingWeapon)两个参数可能会在客户端与武器重叠时,服务器上也会有相同的显示

/** 要标记要复制的内容,我们使用 UPROPERTY 中的 Replicated 说明符。 
在将某个内容标记为 Replicated 之后,我们必须定义一个名为 GetLifetimeReplicatedProps 的新函数 */
/** 返回用于网络复制的属性,这需要被所有具有本机复制属性的 actor 类覆盖 */
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;

/** 属性设置为变量可重复 */
//UPROPERTY(Replicated)
/** 使用复制指定复制函数,通知OnRep_OverLappingWeapon调用 */
UPROPERTY(ReplicatedUsing = OnRep_OverLappingWeapon)
class AWeapon* OverLappingWeapon;

UFUNCTION()
void OnRep_OverLappingWeapon(AWeapon* LastWeapon);
void ABlasterCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	/** 指定了具有复制变量的类 和 复制的变量是哪个  */
	DOREPLIFETIME_CONDITION(ABlasterCharacter, OverLappingWeapon, COND_OwnerOnly);
}

void ABlasterCharacter::OnRep_OverLappingWeapon(AWeapon* LastWeapon)
{
	if (OverLappingWeapon)
	{
		OverLappingWeapon->ShowPickupWidget(true);
	}

	if (LastWeapon)
	{
		LastWeapon->ShowPickupWidget(false);
	}
}

 

        xxx.h 

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

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "BlasterCharacter.generated.h"

UCLASS()
class BLASTER_API ABlasterCharacter : public ACharacter
{
	GENERATED_BODY()

public:
	// Sets default values for this character's properties
	ABlasterCharacter();	
	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

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

	/** 要标记要复制的内容,我们使用 UPROPERTY 中的 Replicated 说明符。 
	在将某个内容标记为 Replicated 之后,我们必须定义一个名为 GetLifetimeReplicatedProps 的新函数 */
	/** 返回用于网络复制的属性,这需要被所有具有本机复制属性的 actor 类覆盖 */
	virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;

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

	/* 人物移动函数 */
	void MoveForward(float Value);
	void MoveRight(float Value);
	void Turn(float Value);
	void LookUp(float Value);

private:
	/** 弹簧臂组件类声明 属性设置为在任何地方可视 类别是摄像机 */
	UPROPERTY(VisibleAnywhere, Category = Camera)
	class USpringArmComponent* CameraBoom;

	/** 摄像机类声明 属性设置为在任何地方可视 类别是摄像机 */
	UPROPERTY(VisibleAnywhere, Category = Camera)
	class UCameraComponent* FollowCamera;

	UPROPERTY(EditAnywhere,BlueprintReadOnly,meta = (AllowPrivateAccess = "true"))
	class UWidgetComponent* OverheadWidget;

	/** 属性设置为变量可重复 */
	//UPROPERTY(Replicated)
	/** 使用复制指定复制函数,通知OnRep_OverLappingWeapon调用 */
	UPROPERTY(ReplicatedUsing = OnRep_OverLappingWeapon)
	class AWeapon* OverLappingWeapon;

	UFUNCTION()
	void OnRep_OverLappingWeapon(AWeapon* LastWeapon);

public:	
	//FORCEINLINE void SetOverlappingWeapon(AWeapon* Weapon) { OverLappingWeapon = Weapon; };
	void SetOverlappingWeapon(AWeapon* Weapon);
};

        xxx.cpp

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


#include "BlasterCharacter.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Components/WidgetComponent.h"
#include "Net/UnrealNetwork.h"
#include "Blaster/Weapon/Weapon.h"
#include "Blaster/BlasterComponents/CombatComponent.h"

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

	CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));/** 创建类 */
	CameraBoom->SetupAttachment(GetMesh());/** SetupAttachment()将弹簧臂固定在网格上 GetMesh()获得角色的网格(胶囊体) */
	CameraBoom->TargetArmLength = 600.f;/** 设置臂长 */
	CameraBoom->bUsePawnControlRotation = true;/** 是否控制旋转 */

	FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
	/** 设置附件 将摄像机连接到弹簧臂上,通过USpringArmComponent的指针和USpringArmComponent的名字USpringArmComponent::SocketName*/
	FollowCamera->SetupAttachment(CameraBoom,USpringArmComponent::SocketName);
	/** 跟随摄像头无需使用旋转 旋转在CameraBoom  CameraBoom是FollowCamera的组件 */
	FollowCamera->bUsePawnControlRotation = false;

	bUseControllerRotationYaw = false; /** 不希望角色和控制器一起旋转 */
	GetCharacterMovement()->bOrientRotationToMovement = true; /** 使角色按照原有的方向运动 */

	OverheadWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("OverheadWidget"));
	OverheadWidget->SetupAttachment(RootComponent);
}

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

	//if (OverLappingWeapon)
	//{
	//	OverLappingWeapon->ShowPickupWidget(true);
	//}
}

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

	/* 绑定动作映射 */
	PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);/* 具有一个输入的事件IE_Pressed */
	/* 绑定轴映射 */
	PlayerInputComponent->BindAxis("MoveForward",this,&ABlasterCharacter::MoveForward);
	PlayerInputComponent->BindAxis("MoveRight", this, &ABlasterCharacter::MoveRight);
	PlayerInputComponent->BindAxis("Turn", this, &ABlasterCharacter::Turn);
	PlayerInputComponent->BindAxis("LookUp", this, &ABlasterCharacter::LookUp);
}

void ABlasterCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	/** 指定了具有复制变量的类 和 复制的变量是哪个  */
	DOREPLIFETIME_CONDITION(ABlasterCharacter, OverLappingWeapon, COND_OwnerOnly);
}

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

void ABlasterCharacter::MoveForward(float Value)
{
	/* Controller理解成一个人物的控制器 */
	if (Controller != nullptr && Value != 0.f)
	{
		/* 获得旋转方向 */
		const FRotator YawRotation(0.f, Controller->GetControlRotation().Yaw, 0.f);
		/* 从旋转方向创建旋转矩阵FRotationMatrix(YawRotation) 称其为单位轴GetUnitAxis(EAxis::X),返回一个F向量 */
		const FVector Direction(FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X));
		/*沿给定世界方向向量(通常归一化)添加运动输入,按 'ScaleValue' 缩放。
		如果 ScaleValue < 0,则移动方向相反。Base Pawn 类不会自动应用移动,
		在 Tick 事件中,这取决于用户是否这样做。Character 和 DefaultPawn 等子类会自动处理此输入并移动*/
		AddMovementInput(Direction, Value);
	}
}

void ABlasterCharacter::MoveRight(float Value)
{
	if (Controller != nullptr && Value != 0.f)
	{
		const FRotator YawRotation(0.f, Controller->GetControlRotation().Yaw, 0.f);
		const FVector Direction(FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y));
		/*沿给定世界方向向量(通常归一化)添加运动输入,按 'ScaleValue' 缩放。
		如果 ScaleValue < 0,则移动方向相反。Base Pawn 类不会自动应用移动,
		在 Tick 事件中,这取决于用户是否这样做。Character 和 DefaultPawn 等子类会自动处理此输入并移动*/
		AddMovementInput(Direction, Value);
	}
}

void ABlasterCharacter::Turn(float Value)
{
	/*如果是本地 PlayerController,
	则将输入(影响 Yaw)添加到控制器的 ControlRotation。
	此值乘以 PlayerController 的 InputYawScale 值。*/
	AddControllerYawInput(Value);
}

void ABlasterCharacter::LookUp(float Value)
{
	/*如果它是本地 PlayerController,
	则将输入(影响 Pitch)添加到控制器的 ControlRotation。
	此值乘以 PlayerController 的 InputPitchScale 值*/
	AddControllerPitchInput(Value);
}

void ABlasterCharacter::OnRep_OverLappingWeapon(AWeapon* LastWeapon)
{
	if (OverLappingWeapon)
	{
		OverLappingWeapon->ShowPickupWidget(true);
	}

	if (LastWeapon)
	{
		LastWeapon->ShowPickupWidget(false);
	}
}

void ABlasterCharacter::SetOverlappingWeapon(AWeapon* Weapon)
{
	if (OverLappingWeapon)
	{
		OverLappingWeapon->ShowPickupWidget(false);
	}
	OverLappingWeapon = Weapon;

	if (IsLocallyControlled())
	{
		if (OverLappingWeapon)
		{
			OverLappingWeapon->ShowPickupWidget(true);
		}
	}
}

标签:重叠,AWeapon,void,碰撞,笔记,AreaSphere,设置,UE5,include
From: https://blog.csdn.net/m0_53219246/article/details/141091248

相关文章

  • Java学习笔记4--Java跨平台原理
    一、Java程序运行机制计算机高级语言按照程序的执行方式可以分为编译型语言和解释型语言。编译型语言:编写的程序源代码需要通过编译器生成机器语言目标文件,在计算机上直接执行目标文件。编译型语言的代表是C、C++等。解释型语言:源代码被解释器逐行解释并执行,因此无需编译器生......
  • 积性函数和狄利克雷卷积学习笔记
    积性函数和狄利克雷卷积学习笔记积性函数定义若函数\(f(x)\)满足\(f(ab)=f(a)f(b)\),其中\(a,b\)互质,我们称这个函数是积性函数。若\(a,b\)不互质则是完全积性函数。常见积性函数狄利克雷卷积定义也叫狄利克雷乘积。形如下式:\[h(n)=\sum_{ab=n,a>0,b>0}f(a)g(b)\]......
  • Java学习笔记3--java编译和运行的CMD命令
    windows下利用cmd命令行可以调用jdk里的javac.exe和java.exe对java文件进行编译和执行,前提是jdk已成功安装并正确配置相关环境变量执行命令解析:javac命令用于将java源文件编译为class字节码文件,如:javacHelloWorld.java。运行javac命令后,如果成功编译没有错误的话,会出现......
  • 《ImageNet: A Large-Scale Hierarchical Image Database》李飞飞论文阅读笔记
    OpenSNN开思通智网,官网地址:https://w3.opensnn.com/2024年8月份"O站创作者招募计划"快来O站写文章,千元大奖等你来拿!“一起来O站,玩转AGI!”论文地址:《ImageNet:ALarge-ScaleHierarchicalImageDatabase》这篇论文是关于一个叫做“ImageNet”的大型图像数据库的介绍。......
  • opencv学习笔记(一)
    前言本文为本人观看b站视频学习opencv的笔记分享,如有错误欢迎指正,如有侵权联系我删除,视频链接一、ReadImagesVideosandWebcams#include<opencv2/imgcodecs.hpp>#include<opencv2/highgui.hpp>#include<opencv2/imgproc.hpp>#include<iostream>usingnamespaces......
  • 《数据资产管理核心技术与应用》读书笔记-第三章:数据血缘
    《数据资产管理核心技术与应用》是清华大学出版社出版的一本图书,全书共分10章,第1章主要让读者认识数据资产,了解数据资产相关的基础概念,以及数据资产的发展情况。第2~8章主要介绍大数据时代数据资产管理所涉及的核心技术,内容包括元数据的采集与存储、数据血缘、数据质量、数据监控与......
  • Java基础-学习笔记08
    01类变量、类方法、main方法、代码块类变量(静态变量)类变量也叫静态变量/静态属性,是该类的所有对象共享的变量,任何一个该类对象去访问它时,取到的都是相同的值,同样任何一个该类的对象去修改它时,修改的也是同一个变量。关于静态变量在内存中的存放地址,有两种说法,①认为静态变量......
  • leetcode刷题笔记8.5-8.9
    刷题笔记8.5-8.9刷题顺序依照labuladong算法小抄两数之和(8.5)初始化数组:int[]num=newint<length>;int[]num={1,2,3,4};其中数组名代表指针变量,故不可以直接将数组名a赋值给数组名b错误的复制:int[]b=a;数组元素复制:假设数组nums的元素复制到numsSort中:int[]......
  • 结构开发笔记(二):solidworks软件(一):介绍、下载和安装过程
    前言  部分零件外壳需要结构设计,在proE和solidworks中经过过程对比发现solidworks相对比较符合使用习惯,所以在有proE基础的前提下还是更换了solidworks来进行产品的结构零件设计,其图形直接可以进行3D打印,实现定制化的零件。  本篇介绍solidworks,下载并安装。 Solidwo......
  • 结构开发笔记(三):solidworks软件(二):小试牛刀,绘制一个立方体
    前言  solidworks草图大师,基本的使用过程。  所有的零件基础都是从平面绘制开始,然后凸出来厚度。  本篇绘制一个简单的立方体,熟悉基本操作。 立方体绘制过程  选取一个平面绘制一个立方形,然后拉伸即可。  绘制矩形的方式:    功能所见即所得。  其......