#include "SpaceShooterGameMode.h" #include "SpaceshipPawn.h" #include "EnemySpaceship.h" #include "Kismet/GameplayStatics.h" ASpaceShooterGameMode::ASpaceShooterGameMode() { // Set default pawn class using the inherited DefaultPawnClass static ConstructorHelpers::FClassFinder PlayerPawnBPClass(TEXT("/Game/Blueprints/BP_SpaceshipPawn")); if (PlayerPawnBPClass.Class != nullptr) { DefaultPawnClass = PlayerPawnBPClass.Class; } // Find enemy blueprint class static ConstructorHelpers::FClassFinder EnemyBPClass(TEXT("/Game/Blueprints/BP_EnemySpaceship")); if (EnemyBPClass.Class != nullptr) { EnemyClass = EnemyBPClass.Class; } // Enable Tick() PrimaryActorTick.bCanEverTick = true; // Debug message if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, TEXT("GameMode Constructor")); } } void ASpaceShooterGameMode::StartPlay() { Super::StartPlay(); // Start spawning enemies GetWorldTimerManager().SetTimer(EnemySpawnTimer, this, &ASpaceShooterGameMode::SpawnEnemy, EnemySpawnInterval, true); // Debug message if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("GameMode StartPlay")); } } void ASpaceShooterGameMode::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void ASpaceShooterGameMode::SpawnEnemy() { // Count current enemies TArray FoundEnemies; UGameplayStatics::GetAllActorsOfClass(GetWorld(), AEnemySpaceship::StaticClass(), FoundEnemies); // Only spawn if we haven't reached the maximum if (FoundEnemies.Num() < MaxEnemies) { UWorld* World = GetWorld(); if (World && EnemyClass) { FVector SpawnLocation = GetRandomSpawnLocation(); FRotator SpawnRotation = FRotator::ZeroRotator; FActorSpawnParameters SpawnParams; SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn; // Spawn using the Blueprint class instead of the C++ class directly AEnemySpaceship* NewEnemy = World->SpawnActor(EnemyClass, SpawnLocation, SpawnRotation, SpawnParams); } } } FVector ASpaceShooterGameMode::GetRandomSpawnLocation() { APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); if (PlayerController && PlayerController->GetPawn()) { FVector PlayerLocation = PlayerController->GetPawn()->GetActorLocation(); // Generate random angle float Angle = FMath::RandRange(0.0f, 2.0f * PI); // Generate random radius between min and max float Radius = FMath::RandRange(MinSpawnRadius, MaxSpawnRadius); // Calculate spawn position in a circle around the player FVector SpawnLocation; SpawnLocation.X = PlayerLocation.X + Radius * FMath::Cos(Angle); SpawnLocation.Y = PlayerLocation.Y + Radius * FMath::Sin(Angle); SpawnLocation.Z = PlayerLocation.Z; return SpawnLocation; } return FVector::ZeroVector; }