UEC++常用代码

1.组件


1)静态网格体

UPROPERTY() 
class UStaticMeshComponent* Mesh;
//源文件
#include "Components/StaticMeshComponent.h"
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));


2)粒子组件

UPROPERTY()
class UParticleSystemComponent* MyParticle;
//源文件
#include "Particles/ParticleSystemComponent.h"
MyParticle = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("MyParticle"));

 
3)音频组件

UPROPERTY()
class UAudioComponent* MyAudio;
//源文件
#include "Components/AudioComponent.h"
MyAudio = CreateDefaultSubobject<UAudioComponent>(TEXT("MyAudio"));


 4)碰撞盒子组件

UPROPERTY()
class UBoxComponent* MyBox;
//源文件
#include "Components/BoxComponent.h"
MyBox = CreateDefaultSubobject<UBoxComponent>(TEXT("MyBox"));
MyBox->SetBoxExtent(FVector(1000.0f, 1000.0f, 100.0f));


5)球形碰撞

UPROPERTY()
USphereComponent* CollisionComponent;
//源文件
#include "Components/SphereComponent.h"
// 用球体进行简单的碰撞展示。
CollisionComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent"));
// 设置球体的碰撞半径。
CollisionComponent->InitSphereRadius(15.0f);


 6)发射物移动组件

// 发射物移动组件。
UPROPERTY(VisibleAnywhere, Category = Movement)
UProjectileMovementComponent* ProjectileMovementComponent;
//源文件
#include "GameFramework/ProjectileMovementComponent.h"
 // 使用此组件驱动发射物的移动。
    ProjectileMovementComponent = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileMovementComponent"));
    //更新组件(参数)的位置,通常是更新actor根组件的位置
    ProjectileMovementComponent->SetUpdatedComponent(CollisionComponent);
    //发射物初始速度
    ProjectileMovementComponent->InitialSpeed = 3000.0f;
    //发射物最高速度
    ProjectileMovementComponent->MaxSpeed = 3000.0f;
    //发射物的选择在每一帧进行更新
    ProjectileMovementComponent->bRotationFollowsVelocity = true;
    //设置反弹
    ProjectileMovementComponent->bShouldBounce = true;
    //反弹系数
    ProjectileMovementComponent->Bounciness = 0.3f;
    //发射物重量
    ProjectileMovementComponent->ProjectileGravityScale = 0.0f;

7)弹簧臂

UPROPERTY()
class USpringArmComponent* SpringArmComp;
//源文件
#include "GameFramework/SpringArmComponent.h"
SpringArmComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArmComponent"));
 
 
//为SpringArm类的变量赋值。
SpringArmComp->SetRelativeLocationAndRotation(FVector(0.0f, 0.0f, 50.0f), FRotator(-60.0f, 0.0f, 0.0f));
SpringArmComp->TargetArmLength = 400.f;
SpringArmComp->bEnableCameraLag = true;
SpringArmComp->CameraLagSpeed = 3.0f


8)1.相机组件

UPROPERTY()
class UCameraComponent* CameraComp;
//源文件
 #include "Camera/CameraComponent.h"
CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent"));
CameraComp->SetupAttachment(SpringArmComp,USpringArmComponent::SocketName);


2.修改相机视野大小

// Called every frame
void ASCharacter::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
    //目标视角面积
    float TargetFov = bWantToZoom ? ZoomedFOV : DefaultsFOV;
    //当前视野面积:当前视野,目标视野,帧数,速度
    float NewFOV = FMath::FInterpTo(CameraComp->FieldOfView, TargetFov, DeltaTime, ZoomInterpSpeed);
    //设置摄像机当前的视角面积
    CameraComp->SetFieldOfView(NewFOV);
}


 9) 推力组件

UPROPERTY()
class UPhysicsThrusterComponent* UpThruster;
//源文件
#include "PhysicsEngine/PhysicsThrusterComponent.h"
#include "Kismet/KismetMathLibrary.h"
UpThruster = CreateDefaultSubobject<UPhysicsThrusterComponent>(TEXT("UpThruster"));
    UpThruster->SetupAttachment(RootComponent);
    UpThruster->ThrustStrength =  980.0f;
    UpThruster->SetAutoActivate(true);
    //x轴指向无人机下方
    UpThruster->SetWorldRotation(UKismetMathLibrary::MakeRotFromX(-this->GetActorUpVector()))


 10)根组件的设置

RootComponent = Mesh


11)绑定根组件和插槽

Paddle1->SetupAttachment(Mesh)
 
Paddle1->SetupAttachment(Mesh, TEXT("Paddle1"));


12)得到胶囊体

#include "Components/CapsuleComponent.h"
GetCapsuleComponent()


13)移动组件

#include "GameFrameWork/CharacterMovementComponent.h"
 
//设置最大行走速度
GetCharacterMovement()->MaxWalkSpeed = 300;


14)骨骼网格组件

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
class USkeletalMeshComponent * MeshComponent;
 
#include "Components/SkeletalMeshComponent.h"
 
MeshComponent = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("MeshComponent"));


15)辐射力组件

//辐射力组件
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
    class URadialForceComponent * RadialForceComp;
 
#include "PhysicsEngine/RadialForceComponent.h"
//构造函数
RadialForceComp = CreateDefaultSubobject<URadialForceComponent>(TEXT("RadialForceComp"));
RadialForceComp->bImpulseVelChange = true;
RadialForceComp->bIgnoreOwningActor = true;
RadialForceComp->bAutoActivate = false;
RadialForceComp->SetupAttachment(RootComponent);
 
 
//其他函数里面
 
//范围力起作用
RadialForceComp->FireImpulse();

2.特效


1)在某个位置生成粒子特效

UPROPERTY()
UParticleSystem * Emitter_Projectile;
//源文件
#include "Runtime/Engine/Classes/Kismet/GameplayStatics.h"
UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), Emitter_Projectile, this->GetTransform());
 
 
//项目中又遇到了一次
//生成特效在命中点
//ImpactEffect:特效 ImpactPoint:打击点 Rotation():打击方向
if (ImpactEffect)
{
   UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.ImpactPoint, Hit.ImpactNormal.Rotation());
}


 2-1)生成声音base

//发射声音
UPROPERTY(EditAnywhere)
class USoundBase * FireSound;
//源文件
#include "Kismet/GamePlayStatics.h"
UGameplayStatics::PlaySoundAtLocation(this, FireSound, this->GetActorLocation(), 2.0f);


 2-2)生成声音 cue

  

 //自爆警告声音特效
    UPROPERTY(EditDefaultsOnly, Category = "TracerBot")
    class USoundCue * SelfDestructSound;
 
    //爆炸特效
    UPROPERTY(EditDefaultsOnly, Category = "TracerBot")
    class USoundCue * ExploedSound;
 
 
    #include "Sound/SoundCue.h"
 
    //发生爆炸声,在actor的位置
    UGameplayStatics::PlaySoundAtLocation(this, ExploedSound, GetActorLocation());
 
    //将自爆警告声音绑定到根组件
    UGameplayStatics::SpawnSoundAttached(SelfDestructSound, RootComponent);


 

3)在组件槽点生成粒子特效

if (MuzzleEffect)
{
  //粒子特效,组件,组件的socket
  UGameplayStatics::SpawnEmitterAttached(MuzzleEffect, MeshComponent, MuzzleSocketName);
}


 

3.输入


1)限制组件类型

UPROPERTY()
TSubclassOf<AFloatingActor> floatingActor;//AFloatingActor是一个类型,这是一个例子


2)character前后左右移动 

void MoveX(float value);
void MoveY(float value);
 
//定义
void APacdotPlayer::MoveX(float value)
{
    //Vlocity是FVector类型
    Vlocity.X = value;
    Vlocity.Y = 0;
 
    //character自带的函数,我们把向量喂给他就可以了
    AddMovementInput(Vlocity);
}
 
void APacdotPlayer::MoveY(float value)
{
    Vlocity.X = 0;
    Vlocity.Y = value;
    AddMovementInput(Vlocity);
}
 
//绑定函数
void APacdotPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);
    PlayerInputComponent->BindAxis("MoveX", this, &APacdotPlayer::MoveX);
    PlayerInputComponent->BindAxis("MoveY", this, &APacdotPlayer::MoveY);
}

4.输出


1)float转string并打印

 

#include "Kismet/KismetSystemLibrary.h"
FString::SanitizeFloat(UpThruster->ThrustStrength);
UKismetSystemLibrary::PrintString(this,FString::SanitizeFloat(UpThruster->ThrustStrength));


 
2)生成Actor

//发射物种类
UPROPERTY(EditAnywhere)
TSubclassOf<class AMissle> Bullet;
//源文件
FTransform firepoint = Mesh->GetSocketTransform(TEXT("Fire"));
GetWorld()->SpawnActor<AMissle>(Bullet, firepoint);
 
 
 
//另一个项目
//生成参数
FActorSpawnParameters SpawnParams;
//参数设置
SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
//抛射物对象,生成位置,方向,生成参数
GetWorld()->SpawnActor<AActor>(ProjectileClass, MuzzleLocation, EyeRotator, SpawnParams);

生成actor并绑定到骨骼组件的插槽上

#include "Engine/World.h"
#include "SWeapen.h"
#include "Components/SkeletalMeshComponent.h"    
//设置生成参数,当生成的actor碰到了其他物体,也要生成
    FActorSpawnParameters Parameters;
    Parameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
    //生成武器actor(类型、位置、方向、参数),并且其地址赋予到指针上
    CurrentWeapen = GetWorld()->SpawnActor<ASWeapen>(StartWeapen, FVector::ZeroVector, FRotator::ZeroRotator, Parameters);
    //设置武器的位置与骨骼的插槽中,并设置主人
    if (CurrentWeapen)
    {
        CurrentWeapen->SetOwner(this);
        CurrentWeapen->AttachToComponent(GetMesh(), FAttachmentTransformRules::SnapToTargetNotIncludingScale,WeaponAttachSoketName);
    }


5.工具


1)timer定时器

//添加一个句柄
FTimerHandle SpwanTimerHandle;
 
#include "Engine/public/TimerManager.h"
 
//要调用的函数
UFUNCTION()
void SpwanHandler();
//源文件
void AEnemySpawner::BeginPlay()
{
    Super::BeginPlay();
    GetWorld()->GetTimerManager().SetTimer(SpwanTimerHandle,this,&AEnemySpawner::SpwanHandler,2.0f,true);
    
}
//还有一种写法
GetWorldTimerManager().SetTimer(VulnerableTimerHandle, this, &APacdotEnermy::SetNormal, Time ,false);
//根据句柄得到对应计时器剩余时间
GetWorldTimerManager().GetTimerRemaining((*Iter)->VulnerableTimerHandle);
//清除对应计时器
GetWorldTimerManager().ClearTimer(VulnerableTimerHandle);

2)添加日志消息

 
#include "Engine/Engine.h"
check(GEngine != nullptr);
 
  // 显示调试消息五秒。 
  // 参数中的-1"键"值类型参数能防止该消息被更新或刷新。
//游戏启动时,StartPlay()将在屏幕上打印一条新的调试消息
//("Hello World, this is FPSGameModeBase!"),采用黄色文本,显示五秒钟。
  GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Yellow, TEXT("Hello World, this is FPSGameMode!"));


3)向量

private:
    FVector Vlocity;
 
//构造函数里这个向量一定是要初始化的
 
Vlocity = FVector(0, 0, 0);


4)重启关卡

GetWorld()->GetFirstLocalPlayerFromController()->ConsoleCommand(TEXT("RestartLevel"));


5)弹道,碰到物体会返回对应的actor

     

  #include "Engine/World.h"
 
        //位置
        FVector EyeLocation;
        //方向
        FRotator EyeRotator;
        //得到眼睛的位置和角度
        MyOwner->GetActorEyesViewPoint(EyeLocation,EyeRotator);
        //弹道的终点就是起点+方向*10000
        FVector TraceEnd = EyeLocation + (EyeRotator.Vector() * 1000);
        //设置碰撞通道为可见性通道
        FCollisionQueryParams  QueryParams;
        //让射线忽略玩家和枪
        QueryParams.AddIgnoredActor(MyOwner);
        QueryParams.AddIgnoredActor(this);
        //符合追踪设为true,可以让射击更加精准
        QueryParams.bTraceComplex = true;
        //LineTraceSingleByChannel击中物体返回true
        GetWorld()->LineTraceSingleByChannel(Hit, EyeLocation, TraceEnd, ECC_Visibility, QueryParams)

6)debug弹道画线

#include "DrawDebugHelpers.h"
 
//方便debug
DrawDebugLine(GetWorld(), EyeLocation, TraceEnd, FColor::Red, false, 1, 0, 1);


7)造成点伤害

         

  //命中对象
            AActor * HitActor = Hit.GetActor();
            //造成点伤害ApplyPointDamage
            //参数分别为命中对象、基础伤害、射击方向、命中信息(命中句柄)、MyOwner->GetInstigatorController(暂时不了解)
            //this(射击者) 和伤害类型 
            UGameplayStatics::ApplyPointDamage(HitActor, 20, EyeRotator.Vector(), Hit,MyOwner->GetInstigatorController(),this, DamageType);


8)控制台变量

static int32 DebugWeaponDrawing = 0;
FAutoConsoleVariableRef CVARDebugWeaponDrawing(
    TEXT("COOP.DebugWeapons"),
    DebugWeaponDrawing,
    TEXT("Draw Debug Line For Weapons"),
    ECVF_Cheat
);


6.事件


1)重叠事件及其绑定

//OverlappedComponent:自身的重叠组件   OtherActor:重叠的对方  OtherComp:对方的组件
    UFUNCTION()
    void OverlapHanler(UPrimitiveComponent*  OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult &  SweepResult);
//源文件
//启动overlap事件
Mesh->SetGenerateOverlapEvents(true);
//重叠事件与函数的绑定,this是自身,后面的是要绑定的函数
Mesh->OnComponentBeginOverlap.AddDynamic(this,&AMissle::OverlapHanler);


2)组件的函数绑定在owner的伤害事件 

void HandleTakeAnyDamage(AActor* DamagedActor, float Damage, const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageCauser);
 
//源文件
void USHealthComponent::HandleTakeAnyDamage(AActor * DamagedActor, float Damage, const UDamageType * DamageType, AController * InstigatedBy, AActor * DamageCauser)
{
    //当前生命值<=0,就不做任何处理
    if (Health <= 0)
    {
        return;
    }
    //承受伤害
    Health = FMath::Clamp(Health - Damage, 0.0f, DefaultHealth);
    
}
 
// Called when the game starts
void USHealthComponent::BeginPlay()
{
    Super::BeginPlay();
 
    Health = DefaultHealth;
    
    AActor * Owner = GetOwner();
    //将该函数绑定在角色的受伤事件上
    if (Owner)
    {
        Owner->OnTakeAnyDamage.AddDynamic(this, &USHealthComponent::HandleTakeAnyDamage);
    }
}

3)自定义扣血事件

DECLARE_DYNAMIC_MULTICAST_DELEGATE_SixParams(FOnHealthChangedSignature, USHealthComponent*, HealthComp, float, Health, float, HealthDelta, const class UDamageType*, DamageType, class AController*, InstigatedBy, AActor*, DamageCauser);
 
//自定义事件的变量
UPROPERTY( BlueprintAssignable, Category = "HealthComponent")
FOnHealthChangedSignature OnHealthChanged;
 
//源文件
void USHealthComponent::HandleTakeAnyDamage(AActor * DamagedActor, float Damage, const UDamageType * DamageType, AController * InstigatedBy, AActor * DamageCauser)
{
    //当前生命值<=0,就不做任何处理
    if (Health <= 0)
    {
        return;
    }
    //承受伤害
    Health = FMath::Clamp(Health - Damage, 0.0f, DefaultHealth);
    UE_LOG(LogTemp, Log, TEXT("Health :%s"), *FString::SanitizeFloat(Health));
    //自定义事件
    OnHealthChanged.Broadcast(this, Health, Damage, DamageType, InstigatedBy, DamageCauser);
}

4)脱离玩家控制

//让玩家控制器与玩家角色分离,并让角色消失(3s)
        DetachFromControllerPendingDestroy();
        SetLifeSpan(3.0f);


7.UPROPERTY

1.EditAnywhere

2.VisibleAnywhere

3.Category

4.BlueprintReadWrite

5.VisibleAnywhere

8.UFUNCTION

1.BlueprintCallable 

2.BlueprintImplementableEvent 

3.BlueprintNativeEvent 

9.迭代器


1.模板迭代器

    //利用迭代,查找场景中有多少食物
    //TActorIterator<APacdot>是类型,PacItr是对象名,(GetWorld())构造函数参数表
    //上述就是简单的创建一个对象的过程
    //我认为PacItr是指向指针的指针,指向APacdot类型的指针
    for (TActorIterator<APacdot> PacItr(GetWorld()); PacItr; ++PacItr)
    {
        PacdotNum++;
    }
    //利用迭代,找到所有敌人
    for (TActorIterator<APacdotEnermy> EneItr(GetWorld()); EneItr; ++EneItr)
    {
        Enermis.Add(Cast<APacdotEnermy>(*EneItr));
    }


2.Iter迭代器

//auto 自动声明对象类型
for (auto Iter(Enermis.CreateIterator()); Iter; ++Iter)
  {
    Cast<AEnermyController>((*Iter)->GetController())->GoToNewDestination();
  }


10.得到游戏模式

//    APacmanGameModeBase 是游戏模式类的子类
class APacmanGameModeBase * ModeBaseRef;
 
 
#include "PacmanGameModeBase.h"
ModeBaseRef = Cast< APacmanGameModeBase>(UGameplayStatics::GetGameMode(this));


11.网络


1)复制成员变量

    //目前玩家手中的武器
    UPROPERTY(Replicated)
    class ASWeapen * CurrentWeapen1;
 
 
    //用于网络同步的函数
    void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
 
void ASCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);
    //同步给所有的客户端和服务器
    DOREPLIFETIME(ASCharacter, CurrentWeapen1);
}


2)客户端向服务器端复制成员函数的执行内容

//让服务器端也执行开火
//Server服务器 Reliable一直连接 WithValidation 验证
UFUNCTION(Server, Reliable, WithValidation)
        void ServerFire();
 
//函数的实现
void ASWeapen::ServerFire_Implementation()
{
    Fire();
}
 
bool ASWeapen::ServerFire_Validate()
{
    return true;
}
 
//在其他函数中调用
//如果不是服务器,就执行ServerFire(),服务器端就有响应
void ASWeapen::Fire()
{
    if (Role < ROLE_Authority)
    {
        ServerFire();
        
    }
    .........

3)服务器端向客户端复制成员函数的执行内容

//要共享的内容
USTRUCT()
struct FHitScanTrace
{
    GENERATED_BODY()
public:
    //弹道的目的坐标
    UPROPERTY()
    FVector_NetQuantize TraceTo;
    //子弹数目:为了让该结构体内容发生变化,结构体才被不断得被网络复制
    UPROPERTY()
    uint8 BrustCounter;
 
};
 
    //网络射击信息 (当HitScanTrace发生改变,就会激活OnRep_HitScanTrace)
    UPROPERTY(ReplicatedUsing = OnRep_HitScanTrace)
    FHitScanTrace HitScanTrace;
 
    //网络复制函数
    UFUNCTION()
    void OnRep_HitScanTrace();
 
    //复制网络射击信息
    void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
 
//让客户端要做的事情
void ASWeapen::OnRep_HitScanTrace()
{
    //调用射击特效
    PlayFireEffects(HitScanTrace.TraceTo);
}
 
void ASWeapen::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);
    //同步给所有的客户端和服务器(DOREPLIFETIME_CONDITION不用同步给自己)
    DOREPLIFETIME_CONDITION(ASWeapen, HitScanTrace,COND_SkipOwner);
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值