前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >UE4新手常用C++API

UE4新手常用C++API

作者头像
Ning@
发布2021-11-10 15:28:26
3.1K0
发布2021-11-10 15:28:26
举报
文章被收录于专栏:烤包子烤包子
//C++暴露给蓝图可编辑
UCLASS(Blueprintable)

//创建FString
FString::Printf(TEXT("aa bb"));

//蓝图调用变量
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )

//限制条件范围
meta = (ClampMin=0.1,ClampMax = 100)

//蓝图识别组件
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "XXX")

//返回物理材质
EPhysicalSurface SurfaceType = UPhysicalMaterial::DetermineSurfaceType(Hit.PhysMaterial.Get());

//开放给编辑器时的类型,而不是某一个引用
TSubClassOf

//软引用
TSoftObjectPtr
TSoftClassPtr 

//蓝图调用函数
UFUNCTION(BlueprintCallable, Category = "XXX")

//设置子Actor
HandObject->SetChildActorClass(ASlAiHandObject::StaticClass());

//继承父类
Super::Xxx();  

//获取组件
GetComponentByClass(UXXXComponent::StaticClass());

//调整Tick间隔为1秒
PrimaryActorTick.TickInterval = 1.0f;

//循环输出
ForEachLoop   FStringaa 
for(FString xx : FStringaa){}

//设置鼠标点击输入模式(controlelr)
FInputModeGameOnly InputMode;
InputMode.SetConsumeCaptureMouseDown(true);
SetInputMode(InputMode);

//碰撞体物理旋转锁定
BoxCollision->GetBodyInstance()->bLockZRotation = true;

//播放音效
UGameplayStatics::SpawnSoundAttached(soundcue,RootComponent);

//向量长度
Fvector.size();

//Widget的初始化函数
public:
    virtual bool Initialize() override;

protected:
    //Widget的tick函数
    virtual void NativeTick(const FGeometry& MyGeometry, float InDeltaTime) override;

//例:
void BeginDestroy() override;

void AmyActor::BeginDestroy()
{
Super::BeginDestroy();
UE_LOG(LogTemp, Warning, TEXT("Game exit!"));
}

//C++调用蓝图函数

//首先创建C++为基类,蓝图继承后创建一个函数Test

#include "OutputDevice.h"

FString cmd = FString::Printf(TEXT("BB CD"));

//BB函数名,CD参数

FOutputDeviceDebug device;
CallFunctionByNameWithArguments(*cmd, device, NULL, true);

//蓝图重载C++函数(可以在C++中其他位置调用一个目前没有任何功能的函数(事件),而该函数的具体实现交给蓝图实现)

UFUNCTION(BlueprintImplementableEvent)       

void OnTest(); 

//在蓝图中Add Event,找到对应的函数名,创建后即可实现具体逻辑

//然后也可以在自己的C++代码中调用该方法

void MyActor::OnPressed()
{
OnTest();
}

//蓝图添加默认的C++实现(C++在调用了SomeFunction()的地方先调用SomeFunction_Implementation的实现,但如果在蓝图中定义了SomeFunction事件(即使后面不连接任何内容),则会忽略C++中SomeFunction_Implementation中的实现,只采用蓝图中的实现)

UFUNCTION(BlueprintNativeEvent, Category = "SomeCategory")

 void SomeFunction();

void AMyActor::SomeFunction_Implementation() 

{ 

UE_LOG(LogTemp, Warning, TEXT("Implenetaion in C++")); 

}

//loadstreamlevel的百分比调用
GetAsyncLoadPercentage(PackageName)

//获取控制器
UGameplayStatics::GetPlayerController(GWorld, 0);(->GetWorld())

//获取默认蓝图类
HUDClass = AXXXHUD::StaticClass();

//判断Actor是蓝图还是C++
Actor->GetClass.IsNative();

//按键
GetWorld()->GetFirstPlayerController()->WasInputKeyJustPressed(Key)
GetWorld()->GetFirstPlayerController()->WasInputKeyJustReleased(Key) 

//确保内容存在,否则中断代码
ensure(XX)

//鼠标在屏幕中的位置
#include "Engine/GameEngine.h"
#include "Engine/Engine.h"

FVector2D MousePosition;

GEngine->GameViewport->GetMousePosition(MousePosition);

MousePosition=MousePosition/DPIScale;

//判断当前游戏运行模式
GetWorld()->WorldType

//失焦后声音还能播放
GConfig->GetFloat(TEXT("Audio"), TEXT("UnfocusedVolumeMultiplier"), UnfocusedVolumeMultiplier, GEngineIni);

//或者在DefaultEngine.ini中添加

[Audio]

UnfocusedVolumeMultiplier=1.0

//加载地图
UGameplayStatics::OpenLevel(GetWorld(), *mapName);

//获取角色位置和方向
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(PawnLocation,PawnRotation);//面朝的方向

//当前帧
#include "Engine/World.h"

GetWorld()->DeltaTimeSeconds

//当前旋转量
this->GetActorForwardVector().Rotation()

//单位向量
PawnRotation.Vector();

PawnVector.GetSafeNormal();

//获取速度
auto ForwardSpeed = FVector::DotProduct(MoveVelocityNormal, AIForwardNormal);

//运行命令行
GetWorld()->GetFirstPlayerController()->ConsoleCommand("quit");

//打印
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Yellow, FString::Printf(TEXT("%s"),*FString));
#include "Misc/OutputDevice.h"
GLog->Logf(TEXT("%s"), *Filepath);

//限制函数
FMath::Clamp(A1 + A2, 0.0, 1.0);

//设置位置
SetActorLocation(FVector(0.0f, 0.0f, 250.0f));

//打开EXE

FPlatformProcess::ExecProcess(*QQ, nullptr, nullptr, nullptr, nullptr);

FPlatformProcess::CreateProc(*QQ, nullptr, true, false, false, nullptr, -1, nullptr, nullptr);

//添加到控制台函数
UFUNCTION(Exec, Category = "AActor")

//覆盖Actor控制台函数
virtual bool ProcessConsoleExec(const TCHAR* Cmd, FOutputDevice& Ar, UObject* Executor) override;

bool UMyGameInstance::ProcessConsoleExec(const TCHAR* Cmd, FOutputDevice& Ar, UObject* Executor)
{
    bool Res = Super::ProcessConsoleExec(Cmd, Ar, Executor);
    if (!Res)
    {
        //获取场景对象方法一: 
        for (TActorIterator It(GetWorld()); It; ++It)
        {
            Res = It->ProcessConsoleExec(Cmd, Ar, Executor);
        }
        //获取场景对象方法二:
        /*TArray ActArray;
        UGameplayStatics::GetAllActorsOfClass(GetWorld(), AMyCharacter::StaticClass(), ActArray);
        for(AActor* Act : ActArray) Act->ProcessConsoleExec(Cmd, Ar, Executor);*/
    }
    return Res;
}

//判断exe是那个端
ENetMode netMode = GetNetMode();

switch(netMode)

{

case NM_Standalone :

print //单独端, 单机游戏

NM_DedicatedServer //专用服务器

NM_ListenServer //监听服务器

NM_Client //客户端

NM_MAX

}

//MD5加密
FMD5::HashAnsiString(TEXT("someStuff"));

//蓝图打印
#include"MessageLog.h"
FMessageLog("DebugLog_FMessageLog").Warning(FText::FromString(MyString));

//生成类
TestObjectActor = GWorld->SpawnActor(TestBlueprint);
UWorld* const World = GetWorld();
AActor* GridCube = World->SpawnActor(GridCubeClass2, FVector(0.0f, 90.0f, 50.0f), FRotator(0.0f, 0.0f, 0.0f));

//读取Texture2D
UTexture2D* texture22 = Cast(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(Path)));

//获得名字
Actor->GetName() == TEXT("FloatActor_1")

//获取相机
GetWorld()->GetFirstPlayerController()->PlayerCameraManager

//强制转换
PTGameInstance = Cast(World->GetGameInstance());

//设置碰撞类型
SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);

//设置碰撞属性
SetCollisionProfileName(FName("NoCollision"));

//设置碰撞属性
MeshFirst->SetCollisionObjectType(ECC_Pawn);
MeshFirst->SetCollisionEnabled(ECollisionEnabled::NoCollision);
MeshFirst->SetCollisionResponseToAllChannels(ECR_Ignore);

//构造函数添加组件
RootComponent = CreateDefaultSubobject(TEXT("Center"));

//动态创建UObject
UMyObject*NewObj=NewObject();

//动态创建Object
FMyObject*NewObj= new FMyObject();

//屏幕大小
GetWorld()->GetFirstPlayerController()->GetViewportSize(ViewportSizeX,ViewportSizeY);

//重力
SetEnableGravity(false);

//随机数
FRandomStream Stream;

//产生新的随机种子
Stream.GenerateNewSeed();
int RandIndex = Stream.RandRange(0, ResourcePath.Num() - 1);

//删除AIController
DetachFromControllerPendingDestroy();

//进入观察者模式
StartSpectatingOnly();

//复制资源
UBehaviorTree* myBehaviorTree = DuplicateObject(object,NULL)

//退出游戏
UKismetSystemLibrary::QuitGame(this, nullptr, EQuitPreference::Quit);

GEngine->Exec(GWorld, *FString("Exit"));

//获取游戏时间
double MyTime = FPlatformTime::Seconds;

//获取时间
FDateTime::Now().ToString();

//链接URL
FString TheURL = "xxxxxxxx";
FPlatformProcess::LaunchURL(*TheURL, nullptr, nullptr);

//创建UI   
"Media", "MediaAssets"
if (nullptr == MainMenuWidget)    
{        
UClass* aa = LoadClass( NULL, TEXT( "Blueprint'/Game/UMG/MainMenu.MainMenu_C'" ) );        
MainMenuWidget = CreateWidget( GetWorld()->GetFirstPlayerController(), aa ); 
}    
MainMenuWidget->AddToViewport(); 

//OR:

UPROPERTY(EditAnywhere, Category = "AA")
        TSubclassOf HUDWidgetClass;

UMyHUDWidget* HUDWidget = CreateWidget(GetWorld(), HUDWidgetClass);

//绘制射线
#include "DrawDebugHelpers.h"

DrawDebugLine(
GetWorld(),
StartLocation1,
EndLocation1,
FColor(255, 0, 0),
false,
0.0f,
0.0f,
10.0f

);

FCollisionQueryParams QueryParameter = FCollisionQueryParams("", false, GetOwner());
FHitResult HitResult;
GetWorld()->LineTraceSingleByChannel(
HitResult,
StartLocation2,
EndLocation2,
FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
QueryParameter
)


//获取IP地址
//需要在build.cs添加Sockets模块
#include "SocketSubsystem.h"
#include "IPAddress.h"
FString IpAddr("NONE");
  bool canBind = false;
  TSharedRef LocalIp = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->GetLocalHostAddr(*GLog, canBind);
  if (LocalIp->IsValid())
  {
IpAddr = LocalIp->ToString(false); //(如果想附加端口就写 ture)
}
return IpAddr;

//添加标签
MyActor.Tags.AddUnique(TEXT("MyTag"));  

//销毁物体
MyActor->Destroy();
MyActor->SetLifeSpan(1);//延迟1S

//截图
FString UMyBlueprintFunctionLibrary::TakeScreenShoot(FString picName, bool bUnique /*= true*/)
{
FString inStr;
FString Filename;
FScreenshotRequest::RequestScreenshot(picName + ".png", false, bUnique);
FString ResultStr = FScreenshotRequest::GetFilename();
ResultStr = FPaths::GetBaseFilename(ResultStr, true);
return ResultStr + ".png";
}

void UMyBlueprintFunctionLibrary::Screenshot(const FString InFilename, bool bInShowUI)
{
FScreenshotRequest SR = FScreenshotRequest();
FString savelocation = FPaths::ConvertRelativePathToFull(FPaths::GameDir());
FString filename = savelocation + FString(TEXT("/Saved/Screenshotss/")) + InFilename + FString(TEXT(".png"));
SR.RequestScreenshot(filename, bInShowUI, false);
}

//写入配置文件,有GEditorIni,GEditorProjectIni,GCompatIni,GlightmassIni,GScalabilityIni,GHardwareIni,GInputIni,GGameIni,GGameUserSettingsIni等(查找CoreGlobals.h)
//写的数据会写到 YourGame\Saved\Config\Windows\Game.ini 中
    const FString WriteSection = "MyCustomSection";
    //String
    GConfig->SetString(
        *WriteSection,
        TEXT("key1"),
        TEXT("Hello world"),
        GGameIni
    );
    GConfig->Flush(false, GGameIni);
//读取配置
if (!GConfig) return 0;
float ValueReceived ;
GConfig->GetFloat(
TEXT("MyCustomSection"),
TEXT("key1"),
ValueReceived,
GGameIni
);
return ValueReceived;

//服务器:

//判断是否在服务端运行

GetWorld()->IsServer()

//网络更新频率

NetUpdateFrequency = 66.0f;

MinNetUpdateFrequency = 33.0f;

//枚举字节化

TEnumAsByte AA;

//让矢量服务器传输不用那么精确

FVector_NetQuantize   vectorr;

//复制变量到服务器

UPROPERTY(Replicated)

//在服务器上运行函数

UFUNCTION(Server, Reliable, WithValidation)//NetMulticast

void Server();

void XXX::ServerFire_Implementation(){}

bool XXX::ServerFire_Validate(){return true;}//完整性检查才用到

//判断是否在服务器上运行(Actor是否主机)

Role == ROLE_Authority

//判断是否在客户端上运行

Role < ROLE_Authority

//服务器变量改了通知客户端调用函数

UPROPERTY(ReplicatedUsing=OnRep_GuardState)

UFUNCTION()
    void OnRep_GuardState();

//规则:所有的客户端  
#include "Net/UnrealNetwork.h"
void XXX::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);

    DOREPLIFETIME(XXX(AActor), 变量);

//DOREPLIFETIME_CONDITION(XXX(AActor), 变量,COND_SkipOwner);
}


/// Slate:/


//创建slate

TSharedPtr MenuHUDWidget;

ASlAiMenuHUD::ASlAiMenuHUD()
{
    if (GEngine && GEngine->GameViewport) {

        SAssignNew(MenuHUDWidget, SSlAiMenuHUDWidget);

        GEngine->GameViewport->AddViewportWidgetContent(SNew(SWeakWidget).PossiblyNullContent(MenuHUDWidget.ToSharedRef()));

    }
}

//播放动画

MenuAnimation = FCurveSequence();
MenuCurve = MenuAnimation.AddCurve(StartDelay, AnimDuration, ECurveEaseFunction::QuadInOut);

MenuAnimation.Play(this->AsShared());

//把图片导入ImageSlot

SOverlay::FOverlaySlot* ImageSlot;

.Expose(ImageSlot)

//点击事件

.OnClicked(this, &XXX::OnClick)

//设置锚点

.Anchors(FAnchors(0.f))

//创建按钮

+ SOverlay::Slot()

[

SNew(SButton)

]

//布局

.HAlign(HAlign_Left)
.VAlign(VAlign_Top)

//创建外部调用Slate

TSharedPtr ZhCheckBox;//.h
SAssignNew(ZhCheckBox,SCheckBox)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档