UE4C++小技巧(六)动态创建网格体,并绑定重叠事件

版本:4.24
第一步:在头文件中前向声明一个UStaticMeshComponent指针,一个UBoxComponent指针,其中UBoxComponent指针用于指向碰撞体,UStaticMeshComponent指针用于指向静态网格物体。

public//静态网格体
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite,Category="Mesh")
	class UStaticMeshComponent* MachineMesh;
	//碰撞体
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Mesh")
	class UBoxComponent* CollisionComp;
	//开始重叠事件
	UFUNCTION()
	void OnOverlapBegin(UPrimitiveComponent* HitComp,AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool  bFromSweep, const FHitResult& SweepResult);
	//重叠结束事件
	UFUNCTION()
	void OnOverlapEnd(UPrimitiveComponent* HitComp, AActor* OtherActor,  UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);

第二步:在cpp文件中为上面两个指针赋值,绑定两个重叠事件
需要先导入两个头文件


#include "Components/StaticMeshComponent.h"
#include "Components/BoxComponent.h"
#include"Engine.h"//用于屏幕输出

然后在构造函数中定义两个

//碰撞体
	CollisionComp = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxCollision"));
	if (CollisionComp)
	{
    
    
		RootComponent = CollisionComp;
		CollisionComp->SetBoxExtent(FVector(200,200,50));//设置大小
		CollisionComp->SetGenerateOverlapEvents(true);//生成重叠事件

		CollisionComp->OnComponentBeginOverlap.AddDynamic(this, &AVendingMachine::OnOverlapBegin);//绑定开始碰撞事件
		CollisionComp->OnComponentEndOverlap.AddDynamic(this, &AVendingMachine::OnOverlapEnd);//绑定结束碰撞事件
	}
	//静态网格物体
	MachineMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SphereBase"));
	if (MachineMesh)
	{
    
    
	//设置为碰撞体的子物体
		MachineMesh->SetupAttachment(CollisionComp);
		//防止生成的网格体位置错乱
		MachineMesh->SetRelativeLocation(FVector(0, 0, 0));
	}

然后定义重叠事件

void YourClass::OnOverlapBegin(UPrimitiveComponent* HitComp, AActor* OtherActor,  UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult)
{
    
    
	GEngine->AddOnScreenDebugMessage(-1,2.0f,Color::Red,FString(TEXT("Begin"));
}
void YourClass::OnOverlapEnd(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
    
    
	GEngine->AddOnScreenDebugMessage(-1,2.0f,Color::Red,FString(TEXT("Begin"));
}

猜你喜欢

转载自blog.csdn.net/qq_41487299/article/details/120377609