In this article, we will start to implement the C++ base class that will be used to represent the enemy cannon.
In the Content Browser, access the TutoPart3 folder that is inside the C++ Classes folder. Right-click on free space and choose the New C++ Class... option.
On the next screen, choose the Actor class as the parent class and click the Next button.
In the Name field, write EnemyCannon. In the Path field, keep the default project folder. Click the Create Class button.
The code below shows the first version of the EnemyCannon.h file. In another article, we will add more variables and functions to count the Hits and destroy the cannon.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "EnemyCannon.generated.h"
class AEnemyProjectile;
class UArrowComponent;
UCLASS()
class TUTOPART3_API AEnemyCannon : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AEnemyCannon();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
USceneComponent* RootScene;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
UStaticMeshComponent* StaticMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
UArrowComponent* ProjectileSpawnLocation;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Cannon)
TSubclassOf<AEnemyProjectile> ProjectileClass;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Cannon)
float FireRate;
APawn* PlayerPawn;
FTimerHandle ShotTimerHandle;
void ShootCannon();
};
The enemy cannon does not leave its position but rotates to always be aiming towards the player's current position. To do this, a reference to the player instance is stored in the PlayerPawn pointer.
It fires projectiles of type AEnemyProjectile or of child classes. The projectile class used by a cannon instance is stored in the ProjectileClass variable.
The ProjectileSpawnLocation variable is a component of type UArrowComponent used to specify the location where the projectile will be created.
The time between cannon shots is stored in seconds in the FireRate variable. This variable will be used in the creation of a Timer (referenced by ShotTimerHandle) that will be calling the ShootCannon() function when the time that is in FireRate passes.
In the next article, we'll look at the contents of the EnemyCannon.cpp implementation file.