01.UE4学习总结.Blueprints to C++.创建项目
创建C++项目
编辑器偏好设置
本次将要用蓝图实现这样一个效果
创建一个继承于Actor的蓝图,蓝图配置如下
然后创建一个继承于Actor的C++类
下一步
这时会在自动生成两个文件,一个头文件和一个C++文件
ConeActor.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "ConeActor.generated.h" UCLASS() class MYPROJECT_API AConeActor final : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AConeActor(); protected: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") USceneComponent* Scene; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UStaticMeshComponent* ConeMesh; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="ConeActor|Anywere") uint8 bIsUp:1; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="ConeActor|Anywere") float MinHigh; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="ConeActor|Anywere") float MaxHigh; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ConeActor") float Max; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="ConeActor") float CurrentZ; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ConeActor") float Speed; public: // Called when the game starts or when spawned virtual auto BeginPlay() -> void override; // Called every frame virtual void Tick(float DeltaTime) override; };
ConeActor.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ConeActor.h" // Sets default values AConeActor::AConeActor() { // 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; Scene = CreateDefaultSubobject(TEXT("Scene")); ConeMesh = CreateDefaultSubobject (TEXT("ConeMesh")); Scene->SetupAttachment(GetRootComponent()); ConeMesh->SetupAttachment(Scene); Speed = 50; Max = 200; } // Called when the game starts or when spawned void AConeActor::BeginPlay() { Super::BeginPlay(); const FVector Location = GetActorLocation(); CurrentZ = Location.Z; MinHigh = Location.Z; MaxHigh = Location.Z + Max; bIsUp = true; } // Called every frame void AConeActor::Tick(const float DeltaTime) { Super::Tick(DeltaTime); const float Var = DeltaTime * Speed; if (bIsUp) { CurrentZ = CurrentZ + Var; } else { CurrentZ = CurrentZ - Var; } FVector Location = GetActorLocation(); Location.Z = CurrentZ; SetActorLocation(Location); if (CurrentZ > MaxHigh) { bIsUp = false; } else if (CurrentZ < MinHigh) { bIsUp = true; } }
编译之后,项目中新建蓝图,继承上面的C++类
然后添加同样的静态网格模型,可以看到这里面没有写蓝图逻辑
Actor放到项目中,实现同样的效果
小提示
Unreal C++常用类命名规范
- 继承UObject的类以大写字母U开头
- 继承AActor的类以大写字母A开头
- 继承Structs的类以大写字母F开头
- 继承Enums的类以大写字母E开头
- 其它的基本都是以大写字母F开头
代码结构和命名约定
- 变量用驼峰命名法,每个单词首字母必须大写
- Boolean类型变量必须以小写字母b开头,bIsUp
- if语句即使只有一行,也需要大括号包起来{}
- 大括号必须是在单独的一行
使用uint8定义布尔变量,可以节省内存,虚幻官方用的都是这种方式
uint8 bIsUp:1;