创建蓝图接口
添加蓝图Class
添加接口用指针
添加宝箱Actor类
添加Mesh类
首先在类后面添加一个公用接口声明
class ACTIONROUGELIKE_API AASItemChest : public AActor , public ISGameplayInterface//添加接口
public内新增变量
public: UPROPERTY(EditAnywhere) float TargetPitch; void Interact_Implementation(APawn* InstigationPawn); // Sets default values for this actor's properties AASItemChest();
添加接口方案
注意,这里的函数前缀名字一定要和接口的指针一致,我在这里浪费了近两个小时时间寻找问题
void Interact_Implementation(APawn* InstigationPawn);
添加默认Mesh
AASItemChest::AASItemChest() { // 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; BaseMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("BaseMesh")); RootComponent = BaseMesh; LidMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("LidMesh")); LidMesh -> SetupAttachment(BaseMesh); TargetPitch = 110.0; }
添加宝箱的旋转
void AASItemChest::Interact_Implementation(APawn* InstigationPawn) { LidMesh->SetRelativeRotation(FRotator(TargetPitch,0,0)); GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("Interact_Implementation")));//输出调试信息 }
添加ActorComp
新建Actor Component
在public内新建指针
public: //新建一个void指针 void PrimaryInteract(); // Sets default values for this component's properties USInteractionComponent();
在.cpp内添加射线功能
void USInteractionComponent::PrimaryInteract() { //射线 FHitResult FHit; //碰撞体 FCollisionObjectQueryParams ObjectQueryParams; ObjectQueryParams.AddObjectTypesToQuery(ECC_WorldDynamic); //获得Actor的所有者 AActor* MyOwner = GetOwner(); FVector Eyelocation; FRotator EyeRotator; //获得Actor所有者的眼睛位置 MyOwner->GetActorEyesViewPoint(Eyelocation,EyeRotator); //设置射线发射位置和结束位置 FVector End = Eyelocation + (EyeRotator.Vector() * 1000); GetWorld()->LineTraceSingleByObjectType(FHit,Eyelocation,End,ObjectQueryParams); DrawDebugLine(GetWorld(),Eyelocation,End,FColor::Green,false,1,0,5); AActor* HitActor = FHit.GetActor(); if(HitActor) { GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("HitActor")));//输出调试信息 if(HitActor->Implements<USGameplayInterface>()) { GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("Implements")));//输出调试信 APawn* MyPawn = Cast<APawn>(MyOwner); ISGameplayInterface::Execute_Interact(HitActor,MyPawn); } } }
在角色类内添加接口与ActorComp
.h内新建接口声明
//设置了一个接口 UPROPERTY(VisibleAnywhere) USInteractionComponent* InteractionComp;
.cpp内添加接口
//将创建的ActorComp绑定在角色上 InteractionComp = CreateDefaultSubobject<USInteractionComponent>("InteractionComp");
添加一个按钮执行输入事件
PlayerInputComponent->BindAction("PrimaryInteraction",IE_Pressed,this,&ASCharacter::PrimaryInteraction);
在最下面添加一个输入事件
void ASCharacter::PrimaryInteraction() { if(InteractionComp) { InteractionComp->PrimaryInteract(); } }
效果图
后记:不清楚为什么CSDN总是会转存失败,发文章真的很痛苦