ue4 ue5 UE<C++>三步在C++中制作射击类游戏(射线检测、接口调用) - FVector CameraPos = PC->
废话不多说
一、创建一个接口
UINTERFACE(MinimalAPI)
class UHurtInterface : public UInterface
{
GENERATED_BODY()
};
/**
* 接口函数要在以下I类中定义
*/
class ANIMTAST_API IHurtInterface
{ 拼多多帮助力入口
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 HurtHP(int32 HP);
};
二、在被调用者身上继承接口并实现接口内的函数
注意调用者、被调用者、接口三者之间的关系
此时我们将接口实现写在了EnemyCharacter对象上,这是被调用者
EnemyCharacter.h
cpp被偷了
#include "EnemyCharacter.generated.h"
//此处省略其他代码
//interface
//重写的接口函数都要添加_Implementation
virtual void HurtHP_Implementation(int32 HurtHP)override;
重写的接口函数都要添加_Implementation,记得定义
接口类初步完成、后续再进行调用
三、射线检测
将接口的调用者写在武器Weapon上,但是要射线检测到后才能调用,射线检测代码以及注释如下:
分两步
AWeaponActor.Cpp
//这个函数的行为就是从摄像机向前方向发射出一条射线
//射线打到物体后调用武器发射射线函数,并把打击的点传给它
//摄像机射线发射函数
void AWeaponActor::FireTheArmmo()
{
//老样子PlayerController
AMainPlayerController* PC = Cast(UGameplayStatics::GetPlayerController(GetWorld(), 0));
if (!PC)
{
//没有就是没有被Player拥有,还在地上没人捡
return;
}
//获取屏幕宽高
int32 Width = 0;
int32 Height = 0;
PC->GetViewportSize(Width, Height);
//将屏幕位置投影到世界
FVector STMPos;
FVector STMDir;
//宽高/2就是屏幕中心点
PC->DeprojectScreenPositionToWorld(Width / 2, Height / 2, STMPos, STMDir);
//老样子PlayerCamera
FVector CameraPos = PC->PlayerCameraManager->GetCameraLocation();
FVector CameraDir = PC->PlayerCameraManager->GetActorForwardVector() * 300;
FHitResult Hit;
//摄像机发射射线,单射线检查,只有一个目标
//Start:CameraPos + CameraDir
//End: CameraPos + STMDir * 5000 ,相机位置往世界方向发射一条5000长的射线
if (GetWorld()->LineTraceSingleByChannel
(Hit1, CameraPos + CameraDir, CameraPos + STMDir * 5000, ECC_Camera))
{
//武器射线发射函数
SimulateFire(Hit1.ImpactPoint);
}
}
//武器发射射线函数,为什么要写一个屏幕射线函数呢?
//因为当屏幕射线打中Actor的时候,武器在往打中Actor的Hit点的方向再发射一条射线,符合游戏逻辑
//而不是“眼睛”发射子弹
//武器射线函数
void AWeaponActor::SimulateFire(FVector TargetPos)
{
//获取枪口位置,当然你也可以在武器的Actor中添加SceneComp来获取开枪的位置
FVector MuzzlePos = WeaponMesh->GetSocketLocation(TEXT("FireSoket"));
//B-A = B->A的方向
FVector FirDir = TargetPos - MuzzlePos;
FirDir.Normalize();
FHitResult Hit;
//枪口发射射线
if (GetWorld()->LineTraceSingleByChannel
(Hit, MuzzlePos, MuzzlePos + FirDir * 5000, ECC_Camera))
{
//注意FString要给指针
FString msg = Hit.GetActor()->GetName();
UE_LOG(LogTemp, Log, TEXT("%s"), *msg);
//检查打中的Actor有没有继承接口,有就TRUE
IHurtInterface* Hurtface = Cast(Hit.Actor);
if (Hurtface)
{
//调用接口重写的函数
Hurtface->HurtHP_Implementation(10);
return;
}
UE_LOG(LogTemp, Log, TEXT("Interface Not call"));
}
}
看看效果图:
能打印出被射线检测到的Actor Name,并且有修改血量也 没有打印 Interface Not call,说明接口已经被调用。
有的时候不知道怎么写代码的话先试着从蓝图拉线,如果能在蓝图实现效果的话那么实现C++也不是难事了,不是吗
文章来源