在头文件中定义网格体组件和重叠组件
UPROPERTY(VisibleAnywhere,Category="Components") UStaticMeshComponent* MeshComp; UPROPERTY(VisibleAnywhere, Category = "Components") UBoxComponent* OverlapComp;
导入头文件
#include "Components/BoxComponent.h" #include "Components/StaticMeshComponent.h" #include "Components/ArrowComponent.h" #include "GameFramework/Character.h" #include "Kismet/GameplayStatics.h"
创建OverlapLaunchPad函数,重叠时发生弹射角色
UFUNCTION() void OverlapLaunchPad(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
定义弹射力度和弹射角度
UPROPERTY(EditInstanceOnly, Category = "LaunchPad") float LaunchStrength; UPROPERTY(EditInstanceOnly, Category = "LaunchPad") float LaunchPitchAngle;
定义一个粒子系统
UPROPERTY(EditDefaultsOnly, Category = "LaunchPad") UParticleSystem* ActivateLaunchPadEffect;
设置重叠组件及其尺寸,设置网格体组件作为基底
OverlapComp = CreateDefaultSubobject<UBoxComponent>(TEXT("OverlapComp")); OverlapComp->SetBoxExtent(FVector(75, 75, 50)); RootComponent = OverlapComp; MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp")); MeshComp->SetupAttachment(RootComponent);
将OverlapLaunchPad函数和OverlapComp绑定在一起
OverlapComp->OnComponentBeginOverlap.AddDynamic(this, &AFPSLaunchPad::OverlapLaunchPad);
初始化弹射力度和弹射角度
LaunchStrength = 1500; LaunchPitchAngle = 35.0f;
实现OverlapLaunchPad函数
void AFPSLaunchPad::OverlapLaunchPad(UPrimitiveComponent * OverlappedComponent, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { FRotator LaunchDirection = GetActorRotation();//获取Actor旋转度 LaunchDirection.Pitch += LaunchPitchAngle;//俯仰角,可以让Actor不直接按旋转量旋转,而是朝着某一角度进行旋转 FVector LaunchVelocity = LaunchDirection.Vector() * LaunchStrength;//弹射速率,将旋转量变为矢量再乘以弹射力度 ACharacter* OtherCharacter = Cast<ACharacter>(OtherActor);//强制转换为Character if (OtherCharacter) { OtherCharacter->LaunchCharacter(LaunchVelocity, true, true);//调用游戏内置的发射函数,后面两个参数可用于重写当前速率,无论从哪个方向走入发射平台都能确保弹射速率的一致性 UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ActivateLaunchPadEffect, GetActorLocation());//原地创建发射器 } else if (OtherComp && OtherComp->IsSimulatingPhysics())//检测角色是否转换失败 { OtherComp->AddImpulse(LaunchVelocity, NAME_None, true);//施加相同速率的推力 UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ActivateLaunchPadEffect, GetActorLocation()); } }