UE4C++学习篇(十六)-- C++接口的使用

在上一篇介绍了射线检测,用于道具的交互,在游戏中,可能会使用同一个按键对不同道具进行交互,通常使用C++接口进行处理。

下面介绍C++接口创建和使用的流程。

创建接口:

 

接口的代码:

#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "SInteractionInterface.generated.h"

// This class does not need to be modified.
UINTERFACE(MinimalAPI)
class USInteractionInterface : public UInterface
{
	GENERATED_BODY()
};

/**
 * 
 */
class ACTIONROUGELIKE_API ISInteractionInterface
{
	GENERATED_BODY()

	// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:

	//C++中声明定义,可在蓝图中重写
	UFUNCTION(BlueprintNativeEvent)
    void Interact(APawn* InstigatorPawn);

 上面的USInteractionInterface类不能修改,在下面的 ISInteractionInterface中创建接口函数,在其他的类中进行使用。

 在角色身上创建一个用于交互的组件,通过这个组件去进行射线检测,如果检测到的物体继承了自定义的C++接口,那么就可以调用重写的交互函数,从而和道具进行交互。

在角色身上创建交互组件:

//自定义的交互组件
InteractComp = CreateDefaultSubobject<USInteractionComponent>(TEXT("InteractComp"));

交互组件创处理线检测:

//基础交互
void PrimaryInteract();
void USInteractionComponent::PrimaryInteract()
{

	//获取该组件的拥有者
	AActor* MyOwner = GetOwner();
	//射线的开始位置和结束位置
	FVector Start;
	FRotator StartRotation;
	MyOwner->GetActorEyesViewPoint(Start,StartRotation);
	FVector End = Start + StartRotation.Vector()*1000.0f;
	//碰撞对象查询
	FCollisionObjectQueryParams ObjectQueryParams;
	ObjectQueryParams.AddObjectTypesToQuery(ECollisionChannel::ECC_WorldDynamic);
	//单通道射线根据对象类型检测
	FHitResult Hit;
	bool BIsTraced = GetWorld()->LineTraceSingleByObjectType(Hit,Start,End, ObjectQueryParams);


	//获取到检测到的对象
	AActor* HitActor = Hit.GetActor();
	if (HitActor)
	{
		//碰撞到的Actor是否有接口类,有的话调用交互接口
		if(HitActor->Implements<USInteractionInterface>())
		{
			APawn* MyPawn = Cast<APawn>(MyOwner);
			ISInteractionInterface::Execute_Interact(HitActor, MyPawn);
		}
	}
	//线段的Debug显示
	FColor Color = BIsTraced ? FColor::Green : FColor::Red;
	DrawDebugLine(GetWorld(),Start,End,Color,false,2.0f,0,2.0f);
}

创建用于交互的道具(ATreasureBox):

 继承自C++接口,添加接口的扩展方法。

 我在自己的例子中是交互之后设置自己的材质。

角色按下F键,进行道具交互。

//交互
PlayerInputComponent->BindAction("Interact",IE_Pressed,this,&ASCharacter::PlayerInteractOthers);

//交互组件调用交互函数
void ASCharacter::PlayerInteractOthers()
{
	if (InteractComp)
	{
		InteractComp->PrimaryInteract();
	}
}

这个就是整个的C++接口的简单使用,具体使用可以在项目里面处理。

猜你喜欢

转载自blog.csdn.net/qq_42597694/article/details/125922017