// Fill out your copyright notice in the Description page of Project Settings.#pragmaonce#include"CoreMinimal.h"#include"UObject/Interface.h"#include"HittedInterface.generated.h"// This class does not need to be modified./**
class UHittedInterface 這個類是為了在UE中使用反射系統(tǒng),不需要處理
*/UINTERFACE(MinimalAPI)classUHittedInterface:publicUInterface{GENERATED_BODY()};/****/classTESTINTERFACE_API IHittedInterface {GENERATED_BODY()// Add interface functions to this class. This is the class that will be inherited to implement this interface.public:/**BlueprintNativeEvent除了實現(xiàn)C++調用藍圖外,同樣會調用一個本地方法,本地方法的實現(xiàn)為 聲明的函數(shù)名+_Implementation在實現(xiàn)中應該是:void hitByProjectile_Implementation()override;這樣就可以實現(xiàn)一次調用,兩個實現(xiàn)(c++實現(xiàn),藍圖實現(xiàn))*/UFUNCTION(BlueprintNativeEvent, BlueprintCallable)voidhitByProjectile();};// Fill out your copyright notice in the Description page of Project Settings.#include"HittedInterface.h"// Add default functionality here for any IHittedInterface functions that are not pure virtual.
新建一個Actord類HittedActor繼承自接口IHittedInterface
// Fill out your copyright notice in the Description page of Project Settings.#pragmaonce#include"CoreMinimal.h"#include"HittedInterface.h"#include"GameFramework/Actor.h"#include"HittedActor.generated.h"UCLASS()classTESTINTERFACE_API AHittedActor :public AActor,public IHittedInterface {GENERATED_BODY()public:// Sets default values for this actor's propertiesAHittedActor();protected:// Called when the game starts or when spawnedvirtualvoidBeginPlay()override;public:// Called every framevirtualvoidTick(float DeltaTime)override;public:voidhitByProjectile_Implementation()override;};// Fill out your copyright notice in the Description page of Project Settings.#include"HittedActor.h"#include"Kismet/KismetSystemLibrary.h"// Sets default valuesAHittedActor::AHittedActor(){// 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;}// Called when the game starts or when spawnedvoidAHittedActor::BeginPlay(){Super::BeginPlay();}// Called every framevoidAHittedActor::Tick(float DeltaTime){Super::Tick(DeltaTime);}voidAHittedActor::hitByProjectile_Implementation(){//在HUD界面顯示內容GEngine->AddOnScreenDebugMessage(-1,2.0, FColor::Red,UKismetSystemLibrary::GetDisplayName(this)+TEXT(" hitting..."));}
voidATestInterfaceProjectile::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse,const FHitResult& Hit){//Actor被子彈擊中后,調用接口IHittedInterface* hitedActor =Cast<IHittedInterface>(OtherActor);if(hitedActor){hitedActor->Execute_hitByProjectile(OtherActor);}// Only add impulse and destroy projectile if we hit a physicsif((OtherActor !=nullptr)&&(OtherActor !=this)&&(OtherComp !=nullptr)&& OtherComp->IsSimulatingPhysics()){OtherComp->AddImpulseAtLocation(GetVelocity()*100.0f,GetActorLocation());Destroy();}}