ue4c++日记9(指定区域生成角色)

目录

创建C++类

 头文件

代码文件

结果


创建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);

}

结果

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值