返回
UE4 C++ 新手入门:触发区键盘开关灯
前端
2024-02-05 13:53:46
随着虚幻引擎不断更新迭代,特性日新月异,新手上手难度也随之提升。作为一名经验丰富的技术博主,我将以独到的视角,用这篇文章带领大家轻松入门 UE4 C++ 开发,并通过一个生动的案例——触发区键盘开关灯——循序渐进地掌握核心知识。
创建 C++ Actor 子类
在 UE4 中,Actor 是游戏世界中的基本元素。创建一个新的 C++ Actor 子类并将其命名为 LightSwitchPushButton。在头文件中,继承自 AActor 并声明一个 UPROPERTY 变量 m_Light。
事件绑定
为了响应玩家的键盘输入,我们需要绑定一个事件。在 LightSwitchPushButton.h 中,声明一个 OnKeyPressed() 事件:
DECLARE_EVENT(LightSwitchPushButton, OnKeyPressed)
在 LightSwitchPushButton.cpp 中,实现 OnKeyPressed() 事件,并在其中切换 m_Light 的状态:
void ALightSwitchPushButton::OnKeyPressed()
{
m_Light->ToggleEnabled();
}
键盘输入处理
在 LightSwitchPushButton.cpp 的 BeginPlay() 中,绑定键盘输入事件:
InputComponent->BindAction("Interact", IE_Pressed, this, &ALightSwitchPushButton::OnKeyPressed);
触发器设置
为了限定键盘输入响应区域,我们需要创建触发器。在场景中,添加一个 Box Trigger,将其命名为 TriggerVolume。在 TriggerVolume 的 Details 面板中,将 Object Types 设置为 Actor,并勾选 LightSwitchPushButton。
完整代码
// LightSwitchPushButton.h
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Components/BoxComponent.h"
#include "Components/PointLightComponent.h"
DECLARE_EVENT(LightSwitchPushButton, OnKeyPressed)
UCLASS()
class ALightSwitchPushButton : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UPointLightComponent* m_Light;
UFUNCTION()
void OnKeyPressed();
};
// LightSwitchPushButton.cpp
#include "LightSwitchPushButton.h"
#include "Components/InputComponent.h"
void ALightSwitchPushButton::OnKeyPressed()
{
m_Light->ToggleEnabled();
}
void ALightSwitchPushButton::BeginPlay()
{
Super::BeginPlay();
InputComponent->BindAction("Interact", IE_Pressed, this, &ALightSwitchPushButton::OnKeyPressed);
}
结语
通过这个生动的案例,我们掌握了 UE4 C++ 开发中的核心概念,包括创建 C++ Actor 子类、事件绑定、键盘输入处理和触发器设置。希望这篇文章能帮助新手快速入门 UE4 C++ 开发,开启游戏开发的精彩旅程。