当前位置: 首页 > article >正文

UEC++ 探索虚幻5笔记(捡金币案例) day12

吃金币案例

创建金币逻辑

  • 之前的MyActor_One.cpp,直接添加几个资源拿着就用
	//静态网格
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
	class UStaticMeshComponent* StaticMesh;
	//球形碰撞体
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
	class USphereComponent* TriggerVolume;
	//粒子系统组件
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable|Particle")
	class UParticleSystemComponent* ParticleEffectsComponent;
	//粒子系统
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable|Particle")
	class UParticleSystem* Particle;
	//声音系统
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable|Sounds")
	class USoundCue* Sound;
	//是否旋转
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable Item|Properties")
	bool bRotate = true;
	//旋转速率
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable Item|Properties")
	float RotationRate = 45.f;
  • 逻辑编写
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyActor_One.h"
#include "Engine/Engine.h"
#include "UObject/ConstructorHelpers.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SphereComponent.h"
#include "Particles/ParticleSystemComponent.h"
#include "MyObjectUE5/MyCharacters/MyCharacter.h"
#include "Kismet/GamePlayStatics.h"
#include "Sound/SoundCue.h"

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

	StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
	RootComponent = StaticMesh;
	
	TriggerVolume = CreateDefaultSubobject<USphereComponent>(TEXT("TriggerVolume"));
	TriggerVolume->SetupAttachment(GetRootComponent());

	ParticleEffectsComponent = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ParticleEffects"));
	ParticleEffectsComponent->SetupAttachment(GetRootComponent());
	
	//设置TriggerVolume碰撞的硬编码
	TriggerVolume->SetCollisionEnabled(ECollisionEnabled::QueryOnly);//设置碰撞类型
	TriggerVolume->SetCollisionObjectType(ECollisionChannel::ECC_WorldStatic);//设置对象移动时其应视为某种物体
	TriggerVolume->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);//设置所有的碰撞响应为忽略
	TriggerVolume->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Overlap);//设置Pawn碰撞响应为重叠
}

// Called when the game starts or when spawned
void AMyActor_One::BeginPlay()
{
	Super::BeginPlay();
	TriggerVolume->OnComponentBeginOverlap.AddDynamic(this, &AMyActor_One::OnOverlapBegin);
	TriggerVolume->OnComponentEndOverlap.AddDynamic(this, &AMyActor_One::OnOverlapEnd);
}

void AMyActor_One::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (OtherActor)
	{
		AMyCharacter* Player = Cast<AMyCharacter>(OtherActor);
		if (Player)
		{
			if (Particle)
			{
				UGameplayStatics::SpawnEmitterAtLocation(this, Particle, GetActorLocation(), FRotator(0.f), true);
			}
			if (Sound)
			{
				UGameplayStatics::PlaySound2D(this, Sound);
			}
			Destroy();
		}
	}
	
}

void AMyActor_One::OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{

}

// Called every frame
void AMyActor_One::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (bRotate)
	{
		FRotator rotator = GetActorRotation();
		rotator.Yaw += RotationRate * DeltaTime;
		SetActorRotation(rotator);
	}
}

角色吃到金币逻辑

  • 给角色类添加一个变量用来记录金币数
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Coin")
int Coin = 0;
  • 将金币的Actor类碰撞处理函数测试一下是否能捡到金币
void AMyActor_One::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (OtherActor)
	{
		AMyCharacter* Player = Cast<AMyCharacter>(OtherActor);
		if (Player)
		{
			if (Particle)
			{
				UGameplayStatics::SpawnEmitterAtLocation(this, Particle, GetActorLocation(), FRotator(0.f), true);
			}
			if (Sound)
			{
				UGameplayStatics::PlaySound2D(this, Sound);
			}
			//吃到金币打印金币数
			Player->Coin++;
			GEngine->AddOnScreenDebugMessage(2, 10, FColor::Red, FString::Printf(TEXT("%d"), Player->Coin));
			Destroy();
		}
	}
}

UE5中的UI控件

  • 新建一个UI控件蓝图后,UE5中的控件蓝图默认是什么都没有要添加一个画布面板之后才能添加控件在蓝图上
    在这里插入图片描述
  • 获取控件就得把控件提升为变量就可以在蓝图中调用了
    在这里插入图片描述
  • 编写获取金币逻辑
    在这里插入图片描述
  • 在关卡蓝图中创建自己的UI就完成啦
    在这里插入图片描述
  • 运行效果
    请添加图片描述

MyCharacter.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 "MyCharacter.generated.h"

UCLASS()
class MYOBJECTUE5_API AMyCharacter : public ACharacter
{
	GENERATED_BODY()

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

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Camera", meta = (AllPrivateAccess = "true"))
	class USpringArmComponent* SpringArm;

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Camera", meta = (AllPrivateAccess = "true"))
	class UCameraComponent* MyCamera;

	//映射绑定
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input", meta = (AllPrivateAccess = "true"))
	class UInputMappingContext* DefaultMappingContext;

	//移动绑定
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input", meta = (AllPrivateAccess = "true"))
	class UInputAction* MoveAction;

	//视角绑定
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input", meta = (AllPrivateAccess = "true"))
	class UInputAction* LookAction;

	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Coin")
	int Coin = 0;
protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	void CharacterMove(const FInputActionValue& value);
	void CharacterLook(const FInputActionValue& value);

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

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

};

MyCharacter.cpp

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


#include "MyCharacter.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "Engine/Engine.h"
#include "MyObjectUE5/MyActors/MyActor_One.h"

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

	GetCharacterMovement()->bOrientRotationToMovement = true;
	GetCharacterMovement()->RotationRate = FRotator(0.f, 500.f, 0.f);
	GetCharacterMovement()->MaxWalkSpeed = 500.f;
	GetCharacterMovement()->MinAnalogWalkSpeed = 20.f;
	GetCharacterMovement()->BrakingDecelerationWalking = 2000.f;

	//相机臂
	SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));
	SpringArm->SetupAttachment(GetRootComponent());
	SpringArm->TargetArmLength = 400.f;
	SpringArm->bUsePawnControlRotation = true;

	//相机
	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	MyCamera->SetupAttachment(SpringArm, USpringArmComponent::SocketName);//附加到末尾
	MyCamera->bUsePawnControlRotation = false;
}

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

void AMyCharacter::CharacterMove(const FInputActionValue& value)
{
	FVector2D MovementVector = value.Get<FVector2D>();//获取速度
	if (Controller!=nullptr)
	{
		FRotator Rotation = Controller->GetControlRotation();
		FRotator YawRotation = FRotator(0, Rotation.Yaw, 0);
		//获取到前后单位向量
		FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		//获取左右单位向量
		FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
		
		AddMovementInput(ForwardDirection, MovementVector.Y);
		AddMovementInput(RightDirection, MovementVector.X);
	}
}

void AMyCharacter::CharacterLook(const FInputActionValue& value)
{
	FVector2D LookAxisVector = value.Get<FVector2D>();
	if (Controller != nullptr)
	{
		//GEngine->AddOnScreenDebugMessage(1, 10, FColor::Red, FString::Printf(TEXT("%f"),(GetControlRotation().Pitch)));
		AddControllerYawInput(LookAxisVector.X);
		if (GetControlRotation().Pitch < 270.f && GetControlRotation().Pitch>180.f && LookAxisVector.Y > 0.f)
		{
			return;
		}
		if (GetControlRotation().Pitch < 180.f && GetControlRotation().Pitch>45.f && LookAxisVector.Y < 0.f)
		{
			return;
		}
		AddControllerPitchInput(LookAxisVector.Y);
		
	}
}

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

}

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

	UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent);
	if (EnhancedInputComponent)
	{
		//移动绑定
		EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &AMyCharacter::CharacterMove);
		EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &AMyCharacter::CharacterLook);
	}
}

MyActor_One.h

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

#pragma once

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

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

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
	class UStaticMeshComponent* StaticMesh;

	UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
	class USphereComponent* TriggerVolume;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable|Particle")
	class UParticleSystemComponent* ParticleEffectsComponent;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable|Particle")
	class UParticleSystem* Particle;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable|Sounds")
	class USoundCue* Sound;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable Item|Properties")
	bool bRotate = true;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interoperable Item|Properties")
	float RotationRate = 45.f;

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;
	UFUNCTION()
	void OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
	UFUNCTION()
	void OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);

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

};

MyActor_One.cpp

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


#include "MyActor_One.h"
#include "Engine/Engine.h"
#include "UObject/ConstructorHelpers.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SphereComponent.h"
#include "Particles/ParticleSystemComponent.h"
#include "MyObjectUE5/MyCharacters/MyCharacter.h"
#include "Kismet/GamePlayStatics.h"
#include "Sound/SoundCue.h"

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

	StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
	RootComponent = StaticMesh;
	
	TriggerVolume = CreateDefaultSubobject<USphereComponent>(TEXT("TriggerVolume"));
	TriggerVolume->SetupAttachment(GetRootComponent());

	ParticleEffectsComponent = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ParticleEffects"));
	ParticleEffectsComponent->SetupAttachment(GetRootComponent());
	
	//设置TriggerVolume碰撞的硬编码
	TriggerVolume->SetCollisionEnabled(ECollisionEnabled::QueryOnly);//设置碰撞类型
	TriggerVolume->SetCollisionObjectType(ECollisionChannel::ECC_WorldStatic);//设置对象移动时其应视为某种物体
	TriggerVolume->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore);//设置所有的碰撞响应为忽略
	TriggerVolume->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Overlap);//设置Pawn碰撞响应为重叠
}

// Called when the game starts or when spawned
void AMyActor_One::BeginPlay()
{
	Super::BeginPlay();
	TriggerVolume->OnComponentBeginOverlap.AddDynamic(this, &AMyActor_One::OnOverlapBegin);
	TriggerVolume->OnComponentEndOverlap.AddDynamic(this, &AMyActor_One::OnOverlapEnd);
}

void AMyActor_One::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (OtherActor)
	{
		AMyCharacter* Player = Cast<AMyCharacter>(OtherActor);
		if (Player)
		{
			if (Particle)
			{
				UGameplayStatics::SpawnEmitterAtLocation(this, Particle, GetActorLocation(), FRotator(0.f), true);
			}
			if (Sound)
			{
				UGameplayStatics::PlaySound2D(this, Sound);
			}
			Player->Coin++;
			GEngine->AddOnScreenDebugMessage(2, 10, FColor::Red, FString::Printf(TEXT("%d"), Player->Coin));
			Destroy();
		}
	}
}

void AMyActor_One::OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{

}

// Called every frame
void AMyActor_One::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (bRotate)
	{
		FRotator rotator = GetActorRotation();
		rotator.Yaw += RotationRate * DeltaTime;
		SetActorRotation(rotator);
	}
}

http://www.kler.cn/a/159939.html

相关文章:

  • Qwen2-VL:发票数据提取、视频聊天和使用 PDF 的多模态 RAG 的实践指南
  • Zotero 6.0 安装包及安装教程
  • Docker 篇-Docker 详细安装、了解和使用 Docker 核心功能(数据卷、自定义镜像 Dockerfile、网络)
  • ubuntu-desktop-24.04上手指南(更新阿里源、安装ssh、安装chrome、设置固定IP、安装搜狗输入法)
  • 爱普生SG-8200CJ可编程晶振在通信设备中的应用
  • pySpark乱码
  • Webgis学习总结
  • 数据增强改进,实现检测目标copypaste,增加目标数据量,提升精度
  • 安全行业招聘信息汇总
  • 浅谈Elasticsearch安全和权限管理
  • Ubuntu下应用软件安装
  • c语言函数与指针
  • Redis 入门、基础。(五种基本类型使用场景)
  • 8、Broker进一步了解
  • OracleRac跨网段修改Public IP/VIP/Private IP/Scan IP
  • c语言经典题目
  • Distilling the Knowledge in a Neural Network(2015.5)(d补)
  • ElasticSearch篇---第三篇
  • Leetcode—383.赎金信【简单】
  • Spring Cloud Gateway与spring-cloud-circuitbreaker集成与理解
  • 【IC前端虚拟项目】git和svn项目托管平台的简单使用说明
  • LeetCode Hot100 200.岛屿数量
  • Hadoop学习笔记(HDP)-Part.03 资源规划
  • 【Pytorch使用自制数据集,Dataloader】
  • 7.上传project到服务器及拉取服务器project到本地、更新代码冲突解决
  • Leetcode每日一题学习训练——Python3版(最小化旅行的价格总和)