目录
创建C++类
头文件
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ASPawnVolum.generated.h"
UCLASS()
class TTT_API AASPawnVolum : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AASPawnVolum();
UPROPERTY(VisibleAnywhere,BlueprintReadOnly)
class UBoxComponent* SpawningBox;
UFUNCTION(BlueprintPure)
FVector GetSpawnPoint();
UFUNCTION(BlueprintCallable)
FVector GetSpawnPointDummy(FVector Value);
UPROPERTY(EditAnywhere, BlueprintReadOnly)
TSubclassOf<class AMyCharacter>PawnToSpawn;
//蓝图原生:用来被覆盖,但可用(备胎,随时可以被替代)
UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
void SpawnMyPawn(UClass* PawnClass, FVector const& Location);
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
代码文件
// Fill out your copyright notice in the Description page of Project Settings.
#include "ASPawnVolum.h"
#include "Components/BoxComponent.h"
#include "Kismet/KismetMathLibrary.h"
#include "Engine/World.h"
#include "MyCharacter.h"
// Sets default values
AASPawnVolum::AASPawnVolum()
{
// 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;
SpawningBox = CreateDefaultSubobject<UBoxComponent>(TEXT("123"));
}
FVector AASPawnVolum::GetSpawnPoint()
{
FVector Extent = SpawningBox->GetScaledBoxExtent();//获得缩放后的长宽高
FVector Origin = SpawningBox->GetComponentLocation();//获取组件位置
//随机点
FVector Point = UKismetMathLibrary::RandomPointInBoundingBox(Origin, Extent);//在一个盒体内生成一个随机点
//UE_LOG(LogTemp, Warning, TEXT(" Hit@:x=%s,y=%s,z=%s"), *FString::SanitizeFloat(Point.X), *FString::SanitizeFloat(Point.Y), *FString::SanitizeFloat(Point.Z));
return Point;
}
FVector AASPawnVolum::GetSpawnPointDummy(FVector Value)
{
return FVector();
}
//UClass,UE内的类
void AASPawnVolum::SpawnMyPawn_Implementation(UClass* PawnClass, FVector const& Location)
{
//如果获取到pawn的类,就去获取pawn所在的世界对象,然后在世界对象的点执行生成操作
if (PawnClass) {
UWorld* MyWorld = GetWorld();
if (MyWorld) {
AMyCharacter* Character = MyWorld->SpawnActor<AMyCharacter>(PawnClass, Location, FRotator(0));
}
}
}
// Called when the game starts or when spawned
void AASPawnVolum::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AASPawnVolum::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
结果
扫描二维码关注公众号,回复:
14621112 查看本文章
![](/qrcode.jpg)