UE C++ 斯坦福课程游戏day02

接口

概念

在Unreal Engine中,接口是通过两个类来定义的:一个是UInterface类,另一个是实际的接口类。

  1. USGameplayInterface 是一个UInterface类。这个类主要是用来在Unreal Engine的元系统中注册接口。这个类通常不需要添加任何代码,只需要声明即可。
UINTERFACE(MinimalAPI)
class USGameplayInterface : public UInterface
{
	GENERATED_BODY()
};
  1. ISGameplayInterface 是实际的接口类。这个类中定义了接口的所有函数。当一个类想要实现这个接口时,就需要实现这个类中的所有函数
class FIRSTGAME_API ISGameplayInterface
{
	GENERATED_BODY()

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

总的来说,这两个类的存在是为了在Unreal Engine的系统中更好地支持接口的使用。

例子

制作一个开宝箱的例子。当玩家靠近的时候通过按键进行开启。

  • 了解射线检测碰撞的基本方法
  • 会用接口实现,一些不同的对象的同一函数的不同操作

步骤:
从玩家的视野位置发出碰撞检测射线,检测和谁发生了碰撞,产生的碰撞符合条件的话执行相关的交互操作(旋转等)。

  • 创建宝箱的actor
  • 从玩家视角,发射碰撞检测线。【为了减少玩家的耦合度,新建一个actor组件】
  • 实现接口中定义的交互函数。【在宝箱中actor中】

难点:
在于交互组件。给出关键代码

void USInteractComponent::PrimaryInteract()
{
	UE_LOG(LogTemp,Log,TEXT("调用了交互函数"))
	FCollisionObjectQueryParams ObjectQueryParams; // 碰撞对象查询参数
	ObjectQueryParams.AddObjectTypesToQuery(ECC_WorldDynamic); // 添加动态物体的碰撞查询
	AActor* MyOwner = GetOwner(); //获取当前组件的所有者
	FVector EyeLocation; 
	FRotator EyeRotation; 
	MyOwner->GetActorEyesViewPoint(EyeLocation,EyeRotation);  // 给这个旋转和位置进行赋值
	FVector End = EyeLocation+(EyeRotation.Vector()*1000); // 
	
	TArray<FHitResult> Hits; //碰撞结果的数组
	FCollisionShape Shape; // 碰撞形状
	float Radius = 30.f;
	Shape.SetSphere(Radius);
	bool bBlockingHit = GetWorld()->SweepMultiByObjectType(Hits,EyeLocation,End,FQuat::Identity,ObjectQueryParams,Shape);
	FColor LineColor = bBlockingHit?FColor::Green:FColor::Red;
	for (FHitResult Hit:Hits)
	{
		AActor* HitActor = Hit.GetActor();
		if (HitActor)
		{
			UE_LOG(LogTemp,Log,TEXT("Actor name: %s"), *HitActor->GetName())
			if (HitActor->Implements<USGameplayInterface>()) //注意这是U不是I这是一个接口类
			{
				APawn* MyPawn = Cast<APawn>(MyOwner);
				ISGameplayInterface::Execute_Interact(HitActor,MyPawn);
				
			}
		}
		DrawDebugSphere(GetWorld(),Hit.ImpactPoint,Radius,32,LineColor,false,2.f);
	}
	DrawDebugLine(GetWorld(),EyeLocation,End,LineColor,false,2.f,2.f);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值