(第三周)文章三
生成函数
生成函数有很多重置这里只提一种
GetWorld()->SpawnActor<T>(UClass, FTransform);
子弹类生成
PlayerInputComponent->BindAction(TEXT("Fire"), IE_Pressed, this, &ADrone::DoFire);
void ADrone::DoFire()
{
FTransform fireTrans = Mesh->GetSocketTransform(TEXT("Fire"));
GetWorld()->SpawnActor<AMissle>(Bullet, fireTrans);
}
敌人类生成
设置生成区域
SpawnArea = CreateDefaultSubobject<UBoxComponent>(TEXT("SpawnArea"));
RootComponent = SpawnArea;
SpawnArea->SetBoxExtent(FVector(1000.0f,1000.0f,100.0f));
生成
void AEnemySpawner::SpawnEnemy()
{
FVector origin;
FVector extents;
GetActorBounds(false, origin, extents);
FVector spawnPoint = UKismetMathLibrary::RandomPointInBoundingBox(origin,extents);
GetWorld()->SpawnActor<AEnemy>(EnemyType, spawnPoint,FRotator::ZeroRotator);
}
设置开始生成
void AEnemySpawner::BeginPlay()
{
Super::BeginPlay();
GetWorld()->GetTimerManager().SetTimer(SpawnHandle, this,&AEnemySpawner::SpawnEnemy,spawnSpan,true);
}
h:
#include "GameFramework/Actor.h"
#include "Engine/EngineTypes.h"
#include <LearningProject/Enemy.h>
UPROPERTY(VisibleAnywhere)
class UBoxComponent* SpawnArea;
UPROPERTY(EditAnywhere)
TSubclassOf<AEnemy> EnemyType;
UPROPERTY(EditAnywhere)
float spawnSpan = 1.0f;
private:
FTimerHandle SpawnHandle;
子弹攻击敌人判定
void AMissle::OverlapHandle(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if (OtherActor->IsA<AEnemy>()) {
OtherActor->Destroy();
this->Destroy();
}
}
h:
UFUNCTION()
void OverlapHandle(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);