Let’s create some function and value:
Before: Project Settings --> Input --> Bindings --> Action Mappings --> add “Reload” and R button
- Open your ShooterCharacter.h
1.a) add in public section
FTimerHandle ShootTimer;
1.b) add in private section
void Shoot();
void StopShooting();
void Reload();
bool LeftMouseHeld = true;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Attack", meta = (AllowPrivateAccess = "true"))
int DefaultAmmo;
int Ammo;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Attack", meta = (AllowPrivateAccess = "true"))
float FireRate = 0.5f;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Attack", meta = (AllowPrivateAccess = "true"))
float FireRepeat = 1.0f;
- Open your ShooterCharacter.cpp
2.a) add in top
#include "TimerManager.h"
2.b) add in begin play
Ammo = DefaultAmmo;
2.c) Scroll up find SetupPlayerInputComponent add this
PlayerInputComponent->BindAction(TEXT("Shoot"), EInputEvent::IE_Pressed, this, &AShooterCharacter::Shoot);
PlayerInputComponent->BindAction(TEXT("Shoot"), EInputEvent::IE_Released, this, &AShooterCharacter::StopShooting);
PlayerInputComponent->BindAction(TEXT("Reload"), EInputEvent::IE_Pressed, this, &AShooterCharacter::Reload);
2.d) Scroll Down
void AShooterCharacter::Shoot()
{
if (Ammo != 0)
{
GetWorldTimerManager().SetTimer(ShootTimer, this, &AShooterCharacter::Shoot, FireRepeat, true, FireRate);
Gun->PullTrigger();
Ammo--;
}
else if (Ammo == 0)
{
GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
LeftMouseHeld = true;
Reload();
}
}
void AShooterCharacter::StopShooting()
{
GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
LeftMouseHeld = false;
}
void AShooterCharacter::Reload()
{
UE_LOG(LogTemp, Warning, TEXT("Reloading"));
Ammo = DefaultAmmo;
if(LeftMouseHeld == false)
{
GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
}else
{
LeftMouseHeld = true;
GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
GetWorldTimerManager().SetTimer(ShootTimer, this, &AShooterCharacter::Shoot, FireRepeat, true, FireRate);
}
}