Unreal Engine/GCC Class (5.5.4)

Unreal Engine 5 배워보기 - 37일차

보별 2025. 5. 15. 21:54
반응형

컴퓨터 및 게임 관련 전공인이 아닌 문외한 일반인이 언리얼 엔진을 배우면서 정리한 내용입니다.

그날그날 배웠던 내용을 제가 나중에 보기 위해 정리한 것으로, 지금 당장 보기에 부족한 점이 아주아주 많고 추후에 수정이 될 수도 있습니다.

오탈자 및 잘못 기재된 내용 지적, 부족한 내용 설명은 언제든지 환영입니다.

 

본글은 언리얼 엔진 5.5.4 버전 영문판을 기준으로 합니다.

 

----------------------------------------------------------------------------------------------------------------

 

37일차 학습 내용

- 피격 상태 및 대미지 추가

   플레이어 피격 상태 및 피격 대미지 부여

   적 피격 상태 및 피격 대미지 부여

   대미지 2번 들어가는 현상 해결

 

 

피격 상태 및 대미지 추가

BP에서 사용하는 대미지 관련 노드는 위 그림과 같이 2종류가 있다.

"Apply Damage" 노드는 대상이 대미지를 줄 때 사용하고, "Event AnyDamage" 노드는 대상이 대미지를 받을 때 사용한다.

C++에서도 BP에서 사용하는 노드들과 비슷하게 작동하는 방식으로 코드를 작성하는데, C++에서는 BP보다 세밀하게 설정이 가능해서, 대미지와 관련된 설정은 대부분 C++로 하는 편이다.

플레이어 피격 상태 및 피격 대미지 부여

플레이어가 적에게 피격 당하고 대미지를 받으면 피격 애니메이션과 피격 소리를 재생하며 피격 효과가 나오고, 체력을 감소시키는 코드를 짜보도록 하겠다.

우선은 피격 효과로 Niagara를 이용하기 위해, 위 그림과 같이 프로젝트의 Build.cs로 들어가서 "Niagara" 를 추가해준다.

추가했으면 프로젝트를 닫은 후, 프로젝트 폴더로 가서 프로젝트를 Generate 해주면 된다. 

프로젝트가 재실행되면 플레이어의 체력을 표시할 Widget을 먼저 생성해준다.

20일 차에서 생성해주었던 WBP에서 위 그림과 같이 HP Widget을 추가해준다.

체력을 숫자로만 간단하게 표시할 것이기에, Text Block을 사용하여 숫자만 입력해주었다.

플레이어가 피격했을 때의 상황에 대한 코드는 플레이어의 모든 설정이 들어있는 "PlayerControl" 에서 작성해주면 편하게 작성할 수 있다.

"PlayerControl" 에서 아래와 같이 코드를 입력해준다.

PlayerControl.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "NiagaraSystem.h" // 추가
#include "NiagaraFunctionLibrary.h" // 추가
 
.
.
.
 
public: // ======================================================================Function
 
.
.
.
 
    virtual float TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) override;
    virtual void PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale);
 
public: // ======================================================================PlayerState
 
.
.
.
    float PlayerHP = 100;
 
public: // ======================================================================Widget
 
.
.
.
 
    UTextBlock* HPTextBlock;
 
public: // ======================================================================Effect 피격 효과 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FX")
    TArray<UNiagaraSystem*> HitFXArray;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FX")
    TArray<UParticleSystem*> HitParticleSystemArray;
 
cs

PlayerControl.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "Particles/ParticleSystem.h" //
 
.
.
.
 
void APlayerCharacterControl::BeginPlay()
{
    if (HUDWidget)
    {
 
.
.
.
        HPTextBlock = Cast<UTextBlock>(HUDWidget->GetWidgetFromName(TEXT("HPText"))); // HP Widget 연결
 
.
.
.
 
        if (HPTextBlock)
        {
            HPTextBlock->SetVisibility(ESlateVisibility::Hidden); // 처음에 HP Widget 비가시화
        }
 
.
.
.
}
 
.
.
.
 
float APlayerCharacterControl::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
    const float Damage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser);
 
    GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Red, FString::Printf(TEXT("PlayerDamage : %f"), Damage));
 
    if (Damage > 0)
    {
        PlayerHP -= Damage; // HP 감소
        if (Damage >= 40 /*&& Montage 보유 확인*/// 강공격 피격 애니메이션
        {
            //GetMesh()->GetAnimInstance()->Montage_Play(); // 피격 애니메이션 재생
            UGameplayStatics::PlaySound2D(GetWorld(), HitSound); // 피격 소리 재생; 싱글 게임의 경우 2D, 멀티 게임의 경우 atLocation
        }
        else // 약공격 피격 애니메이션
        {
            //GetMesh()->GetAnimInstance()->Montage_Play();
            UGameplayStatics::PlaySound2D(GetWorld(), HitSound);
        }
        
        if (PlayerHP <= 0// HP = 0 확인
        {
            //GetMesh()->GetAnimInstance()->Montage_Play();
            // UI HP 강제로 0 설정
            return Damage;
        }
        if (HPTextBlock) // HP Widget 수치 플레이어 체력 연결 및 체력 변경 적용 + 가시화
        {
            FText HP = FText::AsNumber(PlayerHP);
            HPTextBlock->SetText(HP);
            HPTextBlock->SetVisibility(ESlateVisibility::Visible);
        }
        
        FVector FXScale = FVector(111);
        PlayHitFX(GetActorLocation(), GetActorRotation(), FXScale);
        
        if (PlayerDamageShakeClass)
        {
            GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(PlayerDamageShakeClass); // Camera Shake 추가
        }        
    }
 
    return Damage;
}
 
void APlayerCharacterControl::PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale)
{
    if (HitFXArray.Num() > 0)
    {
        int32 RandomIndex = FMath::RandRange(0, HitFXArray.Num() - 1);
        UNiagaraSystem* SelectedFX = HitFXArray[RandomIndex];
 
        if (SelectedFX)
        {
            UNiagaraFunctionLibrary::SpawnSystemAtLocation(GetWorld(), SelectedFX, HitLocation);
        }
    }
 
    if (HitParticleSystemArray.Num() > 0)
    {
        int32 RandomIndex = FMath::RandRange(0, HitParticleSystemArray.Num() - 1);
        UParticleSystem* SelectedFX = HitParticleSystemArray[RandomIndex];
 
        if (SelectedFX)
        {
            UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), SelectedFX, HitLocation, HitRotator, FXScale);
        }
    }
}
 
cs

피격 애니메이션은 나중에 넣어줄 것이기에 일단은 제외하고 코드를 작성하였고, 여기까지 작성해주면 플레이어의 피격 상황 및 잔여 체력 계산과 체력 표시 Widget에 관한 설정은 완료되었다.

플레이어가 피격 대미지를 받으려면 적이 공격할 때의 상황에서도 코드를 추가로 입력해줘야한다.

적이 플레이어를 공격할 때의 함수가 "BTTask_Attack" 에 있기에 "BTTask_Attack" 을 아래와 같이 수정해준다.

BTTask_Attack.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void UBTTask_Attack::AttackTrace(ANormalZombie* NormalZombie)
{
 
.
.
.
 
    if (NormalZombie->zombieType == EZombieType::HumanZombie)
    {
        SphereRadius = 100.0f; // 플레이어 피격 판정을 용이하게 하기 위해 크기를 더 크게 함
        Damage = 20;
    }
 
    else if (NormalZombie->zombieType == EZombieType::DogZombie)
    {
        SphereRadius = 100.0f;
        Damage = 10;
    }
 
    else if (NormalZombie->zombieType == EZombieType::WingZombie)
    {
        SphereRadius = 100.0f;
        Damage = 50;
    }
.
.
.
 
 
    if (isHit)
    {
        APlayerCharacterControl* Player = Cast<APlayerCharacterControl>(Hit.GetActor());
        if (Player)
        {
            //Player->TakeDamage(Damage, FDamageEvent(), NormalZombie->GetController(), NormalZombie);
            UGameplayStatics::ApplyDamage(Player, ZombieDamage, Player->GetInstigatorController(), Player, NULL); // 위의 코드를 지우고 해당 줄로 수정
        }
    }
}
cs

코드를 작성하고 컴파일 한 후 게임을 실행해보면, 플레이어가 적에게 피격 당하게 되면 아래 그림과 같이 줄어든 체력이 Widget으로 표시되며 피격 소리, 피격 효과가 나오는 것을 확인할 수 있다.

적 피격 상태 및 피격 대미지 부여

이번엔 위에서 했던 것과 반대로, 적이 플레이어에게 피격 당하고 대미지를 받으면 피격 애니메이션과 피격 소리를 재생하며 피격 효과가 나오고, 체력을 감소시키는 코드를 짜보도록 하겠다.

적이 피격했을 때의 상황에 대한 코드는 적의 체력에 대한 정보가 있는 "ZombieBase" 를 부모로 삼고있고, 적의 애니메이션 및 소리를 관장하는 "Normal Zombie" 에서 작성해주면 편하게 작성할 수 있다.

"Normal Zombie" 에서 아래와 같이 코드를 작성해준다.

NormalZombie.h

1
2
3
4
5
6
7
8
9
10
11
12
public:
    virtual float TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) override;
    virtual void PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale);
 
    UPROPERTY(EditAnywhere, Category = "Sound")
    USoundBase* ZombieHitSound;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    TArray<UAnimMontage*>ZombieHitMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FX")
    TArray<UParticleSystem*> HitParticleSystemArray;
cs

NormalZombie.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
float ANormalZombie::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) // 적의 피격 대미지 추가
{
    const float Damage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser);
 
    GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Blue, FString::Printf(TEXT("ZombieDamage : %f"), Damage));
 
    if (Damage > 0)
    {
        ZombieHP -= Damage;
 
        if (ZombieHitMontage.Num() > 0)
        {
            UAnimInstance* animInstance = GetMesh()->GetAnimInstance(); // 피격 애니메이션 재생
            if (ZombieHitMontage.Num() > 0)
            {
                int randomInt = FMath::RandRange(0, ZombieHitMontage.Num() - 1);
                if (animInstance)
                {
                    animInstance->Montage_Play(ZombieHitMontage[randomInt]);
                }
            }
            UGameplayStatics::PlaySound2D(GetWorld(), ZombieHitSound);
        }
        
 
        if (ZombieHP <= 0)
        {
            //GetMesh()->GetAnimInstance()->Montage_Play();
            // UI HP 강제로 0 설정
            return Damage;
        }
 
        GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Blue, FString::Printf(TEXT("ZombieHP : %f"), ZombieHP));
 
        FVector FXScale = FVector(111);
        PlayHitFX(GetActorLocation(), GetActorRotation(), FXScale);
    }
 
    return Damage;
}
 
void ANormalZombie::PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale) // 적의 피격 이펙트 
{
    if (HitParticleSystemArray.Num() > 0)
    {
        int32 RandomIndex = FMath::RandRange(0, HitParticleSystemArray.Num() - 1);
        UParticleSystem* SelectedFX = HitParticleSystemArray[RandomIndex];
 
        if (SelectedFX)
        {
            UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), SelectedFX, HitLocation, HitRotator, FXScale);
        }
    }
}
cs

코드를 새로 작성할 필요 없이 "PlayerControl" 에서 작성했던 코드를 복사해서 가져와서 일부 부분만 수정해주면 편하게 작성할 수 있다.

적의 피격 상황 및 잔여 체력 계산에 관한 설정은 완료되었다.

플레이어에서 했던 것과 마찬가지로 적이 피격 대미지를 받으려면 플레이어가 공격할 때의 상황에서의 코드를 추가로 입력해줘야한다.

플레이어가 적을 공격할 때의 함수는 "PlayerControl" 에 있기에 "PlayerControl" 을 아래와 같이 수정해준다.

PlayerControl,cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
void APlayerCharacterControl::Fire()
{
    if (isAim)
    {
        float Damage = 10// 기본 대미지를 10으로 지정
 
        if (currentWeapon == EWeaponType::Rifle && RifleBulletCount > 0)
        {
            CurrentBulletCount--;
            RifleBulletCount = CurrentBulletCount;
            Damage = FMath::RandRange(48); // 라이플 사용 중일 때 대미지를 4~8 무작위 값으로 부여
                        
            if (RifleFireCameraShakeClass)
            {
                GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(RifleFireCameraShakeClass);
            }
        }
 
        else if (currentWeapon == EWeaponType::Pistol && PistolBulletCount > 0)
        {
            CurrentBulletCount--;
            PistolBulletCount = CurrentBulletCount;
            Damage = FMath::RandRange(510); // 권총 사용 중일 때 대미지를 5~10 무작위 값으로 부여
            
            if (PistolFireCameraShakeClass)
            {
                GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(PistolFireCameraShakeClass);
            }
        }
 
        else if (currentWeapon == EWeaponType::SMG && SMGBulletCount > 0)
        {
            CurrentBulletCount--;
            SMGBulletCount = CurrentBulletCount;
            Damage = FMath::RandRange(25); // SNG 사용 중일 때 대미지를 2~5 무작위 값으로 부여
            
            if (SMGFireCameraShakeClass)
            {
                GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(SMGFireCameraShakeClass);
            }
        }
 
        OnFire_BP();
        FHitResult Hit;
        FVector StartTrace = Camera->GetComponentLocation();
        FVector EndTrace = StartTrace + (Camera->GetForwardVector() * 1000);
        DrawDebugLine(GetWorld(), StartTrace, EndTrace, FColor::Green, false5.0f);
        if (GetWorld()->LineTraceSingleByChannel(Hit, StartTrace, EndTrace, ECC_GameTraceChannel6))
        {
            UGameplayStatics::ApplyDamage(Hit.GetActor(), Damage, Hit.GetActor()->GetInstigatorController(), Hit.GetActor(), NULL); // 추가
            //Hit.GetActor()->Destroy(); // 피격 액터를 파괴하지 않을 것이기에 주석 처리
        }
 
.
.
.
}
cs

코드를 작성하고 컴파일 한 후 게임을 실행해보면, 적이 플레이어에게 피격 당하게 되면 아래 그림과 같이 피격 애니메이션과 소리, 피격 효과가 나오는 것을 확인할 수 있다.

다만 여기서 문제가 하나 발생했는데, 알 수 없는 이유로 적에게 들어가는 대미지가 '15' 가 한 번 더 들어가는 것을 확인할 수 있다.

대미지 2번 들어가는 현상 해결

해당 문제가 발생한 이유는 예전에 플레이어 BP에서 "Apply Damage" 노드로 대미지를 부여해줬기 때문이다. 

사격 실행 노드의 연결을 끊어주면 위 그림과 같이 정상적으로 대미지가 한 번만출력되는 것을 확인할 수 있다.

 

 

*오늘까지 작성한 코드 정리

PlayerControl.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Fill out your copyright notice in the Description page of Project Settings.
 
#pragma once
 
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h"
#include "Components/Image.h" // UImage 추가
#include "Components/TextBlock.h" // UTextblock 추가
#include "Blueprint/UserWidget.h"
#include "NiagaraSystem.h"
#include "NiagaraFunctionLibrary.h"
#include "PlayerCharacterControl.generated.h"
 
UENUM() // 아이템 목록 Enum
enum class EWeaponType : uint8
{
    None UMETA(DisplayName = "None"),
    Pistol UMETA(DisplayName = "Pistol"),
    SMG UMETA(DisplayName = "SMG"),
    Rifle UMETA(DisplayName = "Rifle"),
    
};
 
 
 
UCLASS()
class MYPROJECT_API APlayerCharacterControl : public ACharacter
{
    GENERATED_BODY()
 
public:
    // Sets default values for this character's properties
    APlayerCharacterControl();
 
protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;
 
public:    
    // Called every frame
    virtual void Tick(float DeltaTime) override;
 
    // Called to bind functionality to input
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
 
 
protected: // ======================================================================Camera
    UPROPERTY(EditAnywhere, BlueprintReadWrite) // readwrite 추가
    class USpringArmComponent* SpringArm;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite) // 총알 발사 수정
    class UCameraComponent* Camera;
 
private: // ======================================================================Input
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputMappingContext* DefaultContext;
 
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputAction* MoveAction;
 
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputAction* LookAction;
 
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputAction* AimAction;
 
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputAction* FireAction;
 
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputAction* OperateAction;
    
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputAction* RifleChangeAction;
 
    UPROPERTY(VisibleAnywhere, Category = "Input")
    class UInputAction* PistolChangeAction;
    
    UPROPERTY(VisibleAnywhere, Category = "Input")
    float mousespeed = 30.0f;
 
public:
    UFUNCTION(BlueprintImplementableEvent, Category = "Input")
    void OnFire_BP(); // 정의 없이 선언만 있음; public으로 해야함! 중요!
 
    UFUNCTION(BlueprintImplementableEvent, Category = "Input"// 줌인 시 크로스헤어 추가 생성
    void OnAim_BP();
 
    UFUNCTION(BlueprintImplementableEvent, Category = "Input"// 줌아웃 시 크로스헤어 추가를 위해 생성
    void OffAim_BP();
 
    UFUNCTION(BlueprintImplementableEvent, Category = "Input")
    void Operate_BP();
 
public: // ======================================================================Function
    void Move(const FInputActionValue& value);
    void Look(const FInputActionValue& value);
    void OnAim();
    void OffAim();
    void Fire();
    void Operate();
    void RifleMode();
    void PistolMode();
 
    void InitFindWidget();
    void InitFindWeaponMesh();
    void InitIsWeaponMap();
    void InitFindInput();
 
    virtual float TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) override;
    virtual void PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale);
    
public: // ======================================================================Anim
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation")
    UAnimMontage* RifleAimMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation")
    UAnimMontage* PistolAimMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation")
    UAnimMontage* RifleFireMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation")
    UAnimMontage* PistolFireMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation")
    UAnimMontage* OperateMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation")
    UAnimMontage* WeaponChangeInMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation")
    UAnimMontage* WeaponChangeOutMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
    TArray<UAnimMontage*> HitMontage;
 
public: // ======================================================================Sound
    UPROPERTY(EditAnywhere, Category = "Sound")
    USoundBase* RifleSound;
 
    UPROPERTY(EditAnywhere, Category = "Sound")
    USoundBase* PistolSound;
 
    UPROPERTY(EditAnywhere, Category = "Sound")
    USoundBase* SMGSound;
 
    UPROPERTY(EditAnywhere, Category = "Sound")
    USoundBase* HitSound;
 
    UPROPERTY(EditAnywhere, Category = "Sound")
    USoundBase* WeaponChangeSound; // 새로 추가
 
    void WeaponFireSound(); // 변수가 아니라 UPROPERTY 추가해주면 안됨
 
private: // ======================================================================Weapon
    UPROPERTY(EditAnywhere)
    class UStaticMeshComponent* SM_RifleWeapon;
 
    UPROPERTY(EditAnywhere)
    class UStaticMeshComponent* SM_PistolWeapon;
 
    UPROPERTY(EditAnywhere)
    class UStaticMeshComponent* SM_SMGWeapon;
 
public:    
    UPROPERTY(EditAnywhere, BlueprintReadOnly) // 초기 상태를 아무것도 들고 있지 않은 상태로 함
    EWeaponType currentWeapon = EWeaponType::None;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite) // 아이템 목록 map 추가
    TMap<EWeaponType, bool> IsWeaponMap;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    int RifleBulletCount = 30;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    int PistolBulletCount = 8;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    int SMGBulletCount = 60;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly) // 장전된 총알
    int CurrentBulletCount = 0;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly) // 소유 중인 총알
    int SaveBulletCount = 0;
 
public: // ======================================================================PlayerState
    UPROPERTY(EditAnywhere, BlueprintReadWrite) 
    bool isItem = false// 아이템 확인 변수 추가
    bool isAim = false;
 
    float PlayerHP = 100;
 
public: // ======================================================================CameraShake
    UPROPERTY(EditAnywhere)
    TSubclassOf<class UCameraShakeBase> RifleFireCameraShakeClass;
 
    UPROPERTY(EditAnywhere)
    TSubclassOf<class UCameraShakeBase> PistolFireCameraShakeClass;
 
    UPROPERTY(EditAnywhere)
    TSubclassOf<class UCameraShakeBase> SMGFireCameraShakeClass;
 
    UPROPERTY(EditAnywhere)
    TSubclassOf<class UCameraShakeBase> PlayerDamageShakeClass;
 
public: // ======================================================================Widget
 
    UPROPERTY(EditAnywhere, Category = "Widget")
    TSubclassOf<class UUserWidget> HUDClass = nullptr;
 
    UPROPERTY()
    class UUserWidget* HUDWidget;
 
    UImage* CrossHairImage;
    UImage* WeaponIconImage;
    UTextBlock* BulletCountTextBlock;
    UTextBlock* HPTextBlock;
 
    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    TMap<EWeaponType, UTexture2D*> WeaponCrosshairImageMap;
    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    TMap<EWeaponType, UTexture2D*> WeaponIconImageMap;
 
public: // ======================================================================Effect
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FX")
    TArray<UNiagaraSystem*> HitFXArray;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FX")
    TArray<UParticleSystem*> HitParticleSystemArray;
};
cs

PlayerControl.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
// Fill out your copyright notice in the Description page of Project Settings.
 
 
#include "PlayerCharacterControl.h"
#include "Components/SkeletalMeshComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "InputMappingContext.h"
#include "Components/StaticMeshComponent.h"
#include "PlayerAnimInstance.h"
#include "Kismet/GameplayStatics.h" // 새로 추가 사운드 추가할 때 소리 재생 시 필수
#include "Engine/DamageEvents.h" // 아이템 습득 시 추가
#include "Blueprint/UserWidget.h" // 위젯 추가
#include "Components/Image.h" // 위젯 내 이미지 불러오기 추가
#include "Internationalization/Text.h" // FText로 변환하기 위해 추가
#include "DoorManager.h" // 문 인식 추가
#include "Particles/ParticleSystem.h"
 
// Sets default values
APlayerCharacterControl::APlayerCharacterControl()
{
     // Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;
 
    ConstructorHelpers::FObjectFinder<USkeletalMesh>PlayerMesh(TEXT("/Script/Engine.SkeletalMesh'/Game/Asset/Player/Survival_Character/Meshes/SK_Survival_Character.SK_Survival_Character'"));
        
    if (PlayerMesh.Succeeded())
    {
        GetMesh()->SetSkeletalMesh(PlayerMesh.Object);  // 스켈레톤 보유
        GetMesh()->SetWorldLocationAndRotation(FVector(00-90), FRotator(0-900)); // 스켈레톤에 이동 및 회전 부여
    }
 
    SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));  // Spring Arm 생성 및 회전 및 각도를 조절하여 Root에 장착
    SpringArm->SetupAttachment(RootComponent);
    SpringArm->SetWorldLocation(FVector(452255.0f));
    SpringArm->TargetArmLength = 200;
    SpringArm->SocketOffset = FVector(23300);
    SpringArm->bUsePawnControlRotation = true;
 
    Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); // Camera 생성 및 Spring Arm에 장착
    Camera->SetupAttachment(SpringArm);
 
    static ConstructorHelpers::FClassFinder<UAnimInstance>AnimInstance(TEXT("/Game/Blueprint/ABP_Player.ABP_Player_C")); // Animation BP 지정; 클래스의 경우는 _C 추가, 경로 상에 '가 들어가있으면 안됨
 
    if (AnimInstance.Class)
    {
        GetMesh()->SetAnimInstanceClass(AnimInstance.Class);
    }
    
    InitFindWeaponMesh();
    InitFindInput();    
}
 
// Called when the game starts or when spawned
void APlayerCharacterControl::BeginPlay()
{
    Super::BeginPlay();
    
    InitFindWidget();
    InitIsWeaponMap();
 
    if (APlayerController* PlayerController = Cast<APlayerController>(GetController())) // PlayerController 관련
    {
        if(UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer()))
        {
            Subsystem->AddMappingContext(DefaultContext, 0);
        }
    }
        
    //SM_Weapon->bHiddenInGame = true;
    //SM_Weapon->IsVisible();
    SM_RifleWeapon->SetVisibility(false);
    SM_PistolWeapon->SetVisibility(false);
 
    if (!HUDWidget && HUDClass) // 게임 실행 시 바로 위젯 생성
    {
        HUDWidget = CreateWidget(GetWorld()->GetFirstPlayerController(), HUDClass);
    }
    if (HUDWidget)
    {
        HUDWidget->AddToViewport();
 
        CrossHairImage = Cast<UImage>(HUDWidget->GetWidgetFromName(TEXT("CrosshairImage")));
        WeaponIconImage = Cast<UImage>(HUDWidget->GetWidgetFromName(TEXT("WeaponIconImage")));
        BulletCountTextBlock = Cast<UTextBlock>(HUDWidget->GetWidgetFromName(TEXT("BulletText")));
        HPTextBlock = Cast<UTextBlock>(HUDWidget->GetWidgetFromName(TEXT("HPText")));
        if (CrossHairImage)
        {
            CrossHairImage->SetVisibility(ESlateVisibility::Hidden);
        }
        if (WeaponIconImage)
        {
            WeaponIconImage->SetVisibility(ESlateVisibility::Hidden);
        }
        if (BulletCountTextBlock)
        {
            BulletCountTextBlock->SetVisibility(ESlateVisibility::Hidden);
        }
        if (HPTextBlock)
        {
            HPTextBlock->SetVisibility(ESlateVisibility::Hidden);
        }
    }
}
 
// Called every frame
void APlayerCharacterControl::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
 
}
 
// Called to bind functionality to input
void APlayerCharacterControl::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) // IMC 관련
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);
    UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent);
    EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &APlayerCharacterControl::Move);
    EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &APlayerCharacterControl::Look);
    EnhancedInputComponent->BindAction(AimAction, ETriggerEvent::Started, this, &APlayerCharacterControl::OnAim); // 조준 관련
    EnhancedInputComponent->BindAction(AimAction, ETriggerEvent::Completed, this, &APlayerCharacterControl::OffAim);
    EnhancedInputComponent->BindAction(FireAction, ETriggerEvent::Started, this, &APlayerCharacterControl::Fire); // 사격 관련
    EnhancedInputComponent->BindAction(OperateAction, ETriggerEvent::Started, this, &APlayerCharacterControl::Operate); // 아이템 감지 관련
    EnhancedInputComponent->BindAction(RifleChangeAction, ETriggerEvent::Started, this, &APlayerCharacterControl::RifleMode);
    EnhancedInputComponent->BindAction(PistolChangeAction, ETriggerEvent::Started, this, &APlayerCharacterControl::PistolMode);
}
 
void APlayerCharacterControl::Move(const FInputActionValue& value) // IA_Move 관련 값 계산
{
    const FVector2D MovementVector = value.Get<FVector2D>();
    const FRotator Rotation = Controller->GetControlRotation();
    const FRotator YawRotation(0, Rotation.Yaw, 0);
        
    const FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
    const FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
 
    AddMovementInput(ForwardDirection, MovementVector.Y);
    AddMovementInput(RightDirection, MovementVector.X);
}
 
void APlayerCharacterControl::Look(const FInputActionValue& value) // IA_Look 관련 값 계산
{
    FVector2D LookAxisVector = value.Get<FVector2D>();
 
    AddControllerYawInput(LookAxisVector.X * GetWorld()->DeltaTimeSeconds * mousespeed);
    AddControllerPitchInput(LookAxisVector.Y * GetWorld()->DeltaTimeSeconds * -mousespeed);
}
 
void APlayerCharacterControl::OnAim() // 조준 상태 애니메이션 연결
{
    if (IsWeaponMap.Num() > 0)
    {
        if (CrossHairImage)
        {
            CrossHairImage->SetVisibility(ESlateVisibility::Visible);
        }
        if (WeaponIconImage)
        {
            WeaponIconImage->SetVisibility(ESlateVisibility::Visible);
        }
        if (BulletCountTextBlock)
        {
            BulletCountTextBlock->SetVisibility(ESlateVisibility::Visible);
        }
                
        if (IsWeaponMap.Contains(EWeaponType::Rifle) && currentWeapon == EWeaponType::Rifle) // 라이플 소유 및 장비 여부 확인
        {
            OnAim_BP();
            UPlayerAnimInstance* animInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance()); // 플레이어에게 값 조정으로 변화하는거 체크용
            isAim = true// 조준 가능
            animInstance->isAim = true;
            CurrentBulletCount = RifleBulletCount; // 추가
            // 무기 상태를 AnimInstance 전달 필요
        }
        else if (IsWeaponMap.Contains(EWeaponType::Pistol) && currentWeapon == EWeaponType::Pistol) // 권총 소유 및 장비 여부 확인
        {
            OnAim_BP();
            UPlayerAnimInstance* animInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance()); // 플레이어에게 값 조정으로 변화하는거 체크용
            isAim = true// 조준 가능
            animInstance->isAim = true;
            CurrentBulletCount = PistolBulletCount;
        }
        else if (IsWeaponMap.Contains(EWeaponType::SMG) && currentWeapon == EWeaponType::SMG) // SMG 소유 및 장비 여부 확인
        {
            OnAim_BP();
            UPlayerAnimInstance* animInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance()); // 플레이어에게 값 조정으로 변화하는거 체크용
            isAim = true// 조준 가능
            animInstance->isAim = true;
            CurrentBulletCount = SMGBulletCount;
        }
 
        FText currentBullet = FText::AsNumber(CurrentBulletCount); // AsNumber를 사용하여 int32 -> FText 변환
        FText saveBullet = FText::AsNumber(SaveBulletCount);
        FText text = FText::Format(FText::FromString(TEXT("{0}/{1}")), currentBullet, saveBullet); // BP에서 사용했던 Format Text와 유사한 방식
 
        BulletCountTextBlock->SetText(text); // BulletCountTextBlock에 현재 총알 / 소유 중 총알 표시
    }
 
}
 
void APlayerCharacterControl::OffAim() // 비조준 상태 애니메이션 연결
{
    if (CrossHairImage)
    {
        CrossHairImage->SetVisibility(ESlateVisibility::Hidden);
    }
    if (WeaponIconImage)
    {
        WeaponIconImage->SetVisibility(ESlateVisibility::Hidden);
    }
    if (BulletCountTextBlock)
    {
        BulletCountTextBlock->SetVisibility(ESlateVisibility::Hidden);
    }
    OffAim_BP();
    UPlayerAnimInstance* animInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance());
    isAim = false// 조준 불가능
    animInstance->isAim = false;
}
 
void APlayerCharacterControl::Fire() // 사격 상태 애니메이션 연결
{
    if (isAim)
    {
        float Damage = 0// 기본 대미지를 10으로 지정
 
        if (currentWeapon == EWeaponType::Rifle && RifleBulletCount > 0// Camera Shake 장탄 수 0일 경우 출력 X
        {
            CurrentBulletCount--;
            RifleBulletCount = CurrentBulletCount; // 줄어든 탄창 수를 저장
            Damage = FMath::RandRange(48); // 대미지를 설정한 범위 내에서 무작위로 부여
                        
            if (RifleFireCameraShakeClass)
            {
                GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(RifleFireCameraShakeClass);
            }
        }
 
        else if (currentWeapon == EWeaponType::Pistol && PistolBulletCount > 0)
        {
            CurrentBulletCount--;
            PistolBulletCount = CurrentBulletCount;
            Damage = FMath::RandRange(510);
            
            if (PistolFireCameraShakeClass)
            {
                GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(PistolFireCameraShakeClass);
            }
        }
 
        else if (currentWeapon == EWeaponType::SMG && SMGBulletCount > 0)
        {
            CurrentBulletCount--;
            SMGBulletCount = CurrentBulletCount;
            Damage = FMath::RandRange(25);
            
            if (SMGFireCameraShakeClass)
            {
                GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(SMGFireCameraShakeClass);
            }
        }
 
        OnFire_BP();
        FHitResult Hit;
        FVector StartTrace = Camera->GetComponentLocation();
        FVector EndTrace = StartTrace + (Camera->GetForwardVector() * 1000);
        DrawDebugLine(GetWorld(), StartTrace, EndTrace, FColor::Green, false5.0f);
        if (GetWorld()->LineTraceSingleByChannel(Hit, StartTrace, EndTrace, ECC_GameTraceChannel6))
        {
            UGameplayStatics::ApplyDamage(Hit.GetActor(), Damage, Hit.GetActor()->GetInstigatorController(), Hit.GetActor(), NULL);
            //Hit.GetActor()->Destroy();
        }
 
        //OnFire_BP(); // BP 동시실행 중요중요중요
        UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();
        if (currentWeapon == EWeaponType::Rifle)
        {
            if (RifleFireMontage)
            {
                AnimInstance->Montage_Play(RifleFireMontage, 0.233333f);
            }
            FTimerHandle FireSoundDelayHandle; // 추가
            GetWorld()->GetTimerManager().SetTimer(FireSoundDelayHandle, this,
                &APlayerCharacterControl::WeaponFireSound,
                0.2f,
                false
            );
        }
        
        else if (currentWeapon == EWeaponType::Pistol)
        {
            if (PistolFireMontage)
            {
                AnimInstance->Montage_Play(PistolFireMontage);
            }
            FTimerHandle FireSoundDelayHandle; // 추가
            GetWorld()->GetTimerManager().SetTimer(FireSoundDelayHandle, this,
                &APlayerCharacterControl::WeaponFireSound,
                0.2f,
                false
            );
        }
    
    }
 
    FText currentBullet = FText::AsNumber(CurrentBulletCount); // Fire에서 소모한 
    FText saveBullet = FText::AsNumber(SaveBulletCount);
    FText text = FText::Format(FText::FromString(TEXT("{0}/{1}")), currentBullet, saveBullet);
 
    BulletCountTextBlock->SetText(text);
}
 
void APlayerCharacterControl::Operate() // 아이템 습득 관리
{
    if (!isItem) // 반대 연산자
    {
        return;
    }
    
    Operate_BP();
 
    FVector StartLocation = GetMesh()->GetSocketLocation("hand_r");
    FVector EndLocation = StartLocation;
    float SphereRadius = 70.0f;
    FHitResult HitResult;
    FCollisionQueryParams Params;
    Params.AddIgnoredActor(this); // 자기자신을 무시
    bool isHit = GetWorld()->SweepSingleByChannel(HitResult, StartLocation, EndLocation, FQuat::Identity, ECC_GameTraceChannel9, FCollisionShape::MakeSphere(SphereRadius), Params);
    /*DrawDebugSphere(GetWorld(), StartLocation, SphereRadius, 12, FColor::Red, false, 1.0f);*/
    if (isHit) // 습득한 아이템과 map의 아이템 일치 여부 확인
    {
        FString name = HitResult.GetActor()->GetName();
 
        name = name.LeftChop(1);
        name = name.LeftChop(name.Len()-name.Find(TEXT("_C_"))); 
        /*if (name.Find(TEXT("BP_")) == 0)
        {
            name = name.RightChop(3);
        }*/
        /*name = name.RightChop(name.Len()-name.Find(TEXT("BP_")));
        name = name.RightChop(3);*/
        /*
        * 만약, name에 BP_가 존재한다면,  -> if
        * 앞에서부터 3개를 잘라라  -> RightChop
        * 
        */
        GEngine->AddOnScreenDebugMessage(-110.0f, FColor::Red, FString::Printf(TEXT("%s"), *name));
 
        if (name==TEXT("BP_Pistol")) // 이름 같은지 체크
        {
            IsWeaponMap[EWeaponType::Pistol] = true;
            //currentWeapon = EWeaponType::Pistol;
        }
        else if(name == TEXT("SMG"))
        {
            IsWeaponMap[EWeaponType::SMG] = true;
            //currentWeapon = EWeaponType::SMG;
        }
        else if (name == TEXT("Rifle"))
        {
            IsWeaponMap[EWeaponType::Rifle] = true;
            //currentWeapon = EWeaponType::Rifle;
        }
        
        else if (name == TEXT("BP_RifleBullet"))
        {
            RifleBulletCount += 30;
            if (RifleBulletCount >= 200)
            {
                RifleBulletCount = 200;
            }
        }
        else if (name == TEXT("BP_PistolBullet"))
        {
            PistolBulletCount += 8;
            if (RifleBulletCount >= 120)
            {
                RifleBulletCount = 120;
            }
        }
        else if (name == TEXT("BP_SMGBullet"))
        {
            SMGBulletCount += 30;
            if (SMGBulletCount >= 200)
            {
                SMGBulletCount = 200;
            }
        }
        else if (name == TEXT("BP_Plate")) // 문 인식
        {
            ADoorManager* doorManager = Cast<ADoorManager>(HitResult.GetActor());
            if (doorManager)
            {
                doorManager->DoorOpen();
            }
 
            return; // 함수를 끝내 아래 삭제 작업이 실행되지 않도록 함
        }
        
        
        FTimerHandle HitDelayHandle;
        GetWorld()->GetTimerManager().SetTimer(HitDelayHandle,
            FTimerDelegate::CreateLambda([HitResult]()
                {
                    HitResult.GetActor()->Destroy();
                }),
            0.5f,
            false
        );
 
        
    }
 
    /*UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();
    if (OperateMontage)
    {
        AnimInstance->Montage_Play(OperateMontage, 1.0f);
    }*/
}
 
void APlayerCharacterControl::RifleMode() // 라이플 장비
{
    GEngine->AddOnScreenDebugMessage(-15.0f, FColor::Blue, TEXT("123"));
    if (IsWeaponMap.Num() > 0 && currentWeapon == EWeaponType::Pistol && IsWeaponMap.Contains(EWeaponType::Rifle))
    {
        if (WeaponChangeInMontage)
        {
            FVector2D currentImagesize = WeaponIconImage->Brush.ImageSize;
            
            if (WeaponIconImage && WeaponIconImageMap[EWeaponType::Rifle] && WeaponIconImageMap.Num() > 0 && WeaponIconImageMap.Contains(EWeaponType::Rifle))
            {
                WeaponIconImage->SetBrushFromTexture(WeaponIconImageMap[EWeaponType::Rifle]);
                WeaponIconImage->SetBrushSize(currentImagesize);
            }
 
 
            if (CrossHairImage && WeaponCrosshairImageMap[EWeaponType::Rifle] && WeaponCrosshairImageMap.Num() > 0 && WeaponCrosshairImageMap.Contains(EWeaponType::Rifle))
            {
                CrossHairImage->SetBrushFromTexture(WeaponCrosshairImageMap[EWeaponType::Rifle]);
                CrossHairImage->SetBrushSize(currentImagesize);
            }
            
            UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();
            float InMontageDuration = AnimInstance->Montage_Play(WeaponChangeInMontage); // 애니메이션 순차 재생을 위해 무기 넣는 애니메이션 재생 후 무기 꺼내는 애니메이션 진행하도록 함
 
                FTimerHandle HideHandle;
                GetWorld()->GetTimerManager().SetTimer(HideHandle,
                    FTimerDelegate::CreateLambda([this]()
                        {
                            if (WeaponChangeSound)
                            {
                                UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
                                //SM_Weapon->bHiddenInGame = false;
                                /*SM_Weapon->IsVisible(); */ // 상태여부
                                SM_PistolWeapon->SetVisibility(false);
                            }
                            if (WeaponChangeOutMontage)
                            {
                                UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();
                                float OutMontageDuration = AnimInstance->Montage_Play(WeaponChangeOutMontage);
 
                                FTimerHandle ShowHandle;
                                GetWorld()->GetTimerManager().SetTimer(ShowHandle,
                                    FTimerDelegate::CreateLambda([this]()
                                        {
                                            if (WeaponChangeSound)
                                            {
                                                UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
                                                SM_RifleWeapon->SetVisibility(true);
                                                UPlayerAnimInstance* playeranimInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance());
                                                playeranimInstance->WeaponTypeCount = 1;
                                                currentWeapon = EWeaponType::Rifle;
                                            }
                                        }),
                                    OutMontageDuration,
                                    false
                                );
                            }
 
                        }),
                    InMontageDuration,
                    false
                );
        }
            else if (IsWeaponMap.Contains(EWeaponType::Rifle) && IsWeaponMap.Num() > 0 && IsWeaponMap[EWeaponType::Rifle] == true)
            {
                if (WeaponChangeOutMontage)
                {
                    FVector2D currentImagesize = WeaponIconImage->Brush.ImageSize;
 
                    if (WeaponIconImage && WeaponIconImageMap[EWeaponType::Rifle] && WeaponIconImageMap.Num() > 0 && WeaponIconImageMap.Contains(EWeaponType::Rifle))
                    {
                        WeaponIconImage->SetBrushFromTexture(WeaponIconImageMap[EWeaponType::Rifle]);
                        WeaponIconImage->SetBrushSize(currentImagesize);
                    }
                
                    if (CrossHairImage && WeaponCrosshairImageMap[EWeaponType::Rifle] && WeaponCrosshairImageMap.Num() > 0 && WeaponCrosshairImageMap.Contains(EWeaponType::Rifle))
                    {
                        CrossHairImage->SetBrushFromTexture(WeaponCrosshairImageMap[EWeaponType::Rifle]);
                        CrossHairImage->SetBrushSize(currentImagesize);
                    }
 
                    UAnimInstance* AnimInstace = GetMesh()->GetAnimInstance();
                    AnimInstace->Montage_Play(WeaponChangeOutMontage);
                }
                FTimerHandle HitDelayHandle;
                GetWorld()->GetTimerManager().SetTimer(HitDelayHandle,
                    FTimerDelegate::CreateLambda([this]()
                        {
                            if (WeaponChangeSound)
                            {
                                UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
                                SM_RifleWeapon->SetVisibility(true);
                                UPlayerAnimInstance* playeranimInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance());
                                playeranimInstance->WeaponTypeCount = 1;
                                currentWeapon = EWeaponType::Rifle;
                            }
                        }),
                    0.5f,
                    false
                );
            }
            else // 총이 없는 경우
            {
                UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
            }    
    }
}
 
void APlayerCharacterControl::PistolMode() // 권총 장비
{
    if (IsWeaponMap.Num() > 0 && currentWeapon == EWeaponType::Rifle && IsWeaponMap.Contains(EWeaponType::Pistol))
    {
        if (WeaponChangeInMontage) // 무기 집어넣는 동작을 먼저 해야하기에 먼저 삽입
        {
            FVector2D currentImagesize = WeaponIconImage->Brush.ImageSize;
            
            if (WeaponIconImage && WeaponIconImageMap[EWeaponType::Pistol] && WeaponIconImageMap.Num() > 0 && WeaponIconImageMap.Contains(EWeaponType::Pistol))
            {
                WeaponIconImage->SetBrushFromTexture(WeaponIconImageMap[EWeaponType::Pistol]);
                WeaponIconImage->SetBrushSize(currentImagesize);
            }
            
            if (CrossHairImage && WeaponCrosshairImageMap[EWeaponType::Pistol] && WeaponCrosshairImageMap.Num() > 0 && WeaponCrosshairImageMap.Contains(EWeaponType::Pistol))
            {
                CrossHairImage->SetBrushFromTexture(WeaponCrosshairImageMap[EWeaponType::Pistol]);
                CrossHairImage->SetBrushSize(currentImagesize);
            }
            
            UAnimInstance* AnimInstace = GetMesh()->GetAnimInstance();
            float InMontageDuration = AnimInstace->Montage_Play(WeaponChangeInMontage);
 
            FTimerHandle HideHandle;
            GetWorld()->GetTimerManager().SetTimer(HideHandle,
                FTimerDelegate::CreateLambda([this]()
                    {
                        if (WeaponChangeSound)
                        {
                            UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
                            SM_RifleWeapon->SetVisibility(false);
                        }
 
                        if (WeaponChangeOutMontage) // 무기 집어넣었으니 무기를 꺼내는 동작 삽입
                        {
                            UAnimInstance* AnimInstace = GetMesh()->GetAnimInstance();
                            float OutMontageDuration = AnimInstace->Montage_Play(WeaponChangeOutMontage);
 
                            FTimerHandle ShowHandle;
                            GetWorld()->GetTimerManager().SetTimer(ShowHandle,
                                FTimerDelegate::CreateLambda([this]()
                                    {
                                        if (WeaponChangeSound)
                                        {
                                            UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
                                            SM_PistolWeapon->SetVisibility(true);
                                            UPlayerAnimInstance* playeranimInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance());
                                            playeranimInstance->WeaponTypeCount = 2;
                                            currentWeapon = EWeaponType::Pistol;
                                        }
                                    }),
                                OutMontageDuration,
                                false
                            );
                        }
                    }),
                InMontageDuration,
                false
            );
        }
    }
 
    else if (IsWeaponMap.Contains(EWeaponType::Pistol) && IsWeaponMap.Num() > 0 && IsWeaponMap[EWeaponType::Pistol] == true)
    {
        if (WeaponChangeOutMontage)
        {
            FVector2D currentImagesize = WeaponIconImage->Brush.ImageSize;
            
            if (WeaponIconImage && WeaponIconImageMap[EWeaponType::Pistol] && WeaponIconImageMap.Num() > 0 && WeaponIconImageMap.Contains(EWeaponType::Pistol))
            {
                WeaponIconImage->SetBrushFromTexture(WeaponIconImageMap[EWeaponType::Pistol]);
                WeaponIconImage->SetBrushSize(currentImagesize);
            }
            
            if (CrossHairImage && WeaponCrosshairImageMap[EWeaponType::Pistol] && WeaponCrosshairImageMap.Num() > 0 && WeaponCrosshairImageMap.Contains(EWeaponType::Pistol))
            {
                CrossHairImage->SetBrushFromTexture(WeaponCrosshairImageMap[EWeaponType::Pistol]);
                CrossHairImage->SetBrushSize(currentImagesize);
            }
 
            UAnimInstance* AnimInstace = GetMesh()->GetAnimInstance();
            AnimInstace->Montage_Play(WeaponChangeOutMontage);
        }
        FTimerHandle HitDelayHandle;
        GetWorld()->GetTimerManager().SetTimer(HitDelayHandle,
            FTimerDelegate::CreateLambda([this]()
                {
                    if (WeaponChangeSound)
                    {
                        UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
                        SM_PistolWeapon->SetVisibility(true);
                        UPlayerAnimInstance* playeranimInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance());
                        playeranimInstance->WeaponTypeCount = 2;
                        currentWeapon = EWeaponType::Pistol;
                    }
                }),
            0.5f,
            false
        );
    }
    else//총이 없는경우++
    {
        UGameplayStatics::PlaySound2D(this, WeaponChangeSound);
    }
}
 
void APlayerCharacterControl::WeaponFireSound() // 사격 소리
{
    if (RifleSound)
    {
        UGameplayStatics::PlaySound2D(this, RifleSound);
 
        //FTimerHandle HitSoundDelayHandle; // 타이머를 제어하기 위한 핸들 변수 (타이머 취소, 타이머 상태 확인) 선언
        //GetWorld()->GetTimerManager().SetTimer(HitSoundDelayHandle, // Get world() 현재 객체가 속한 월드를 가져옴 / GetTimerManager() 타이머를 관리하는 시스템 / SetTimer() 타이머를 설정하고 일정 시간이 지나면 특정 작업을 실행
        //    FTimerDelegate::CreateLambda([this]() { // FTimerDelegate::CreateLambda() 람다변수를 타이머에 연결 가능한 델리게이트로 변환 / [this] 현재 클래스의 멤버 변수 함수에 접근하기 위한 캡쳐 / [=] 모든 외부에 있는 변수 값을 사용함 / () 안에는 내가 원하는 매개변수 삽입가능 / 오류 발생으로 코드 수정
        //        UGameplayStatics::PlaySound2D(this, HitSound);
        //    }),
        //    1.0f, // 1초 뒤
        //    false // 반복 x
        //    ); //소리가 2번 재생되므로 주석처리
        // 람다함수 간단한 함수를 선언 없이 즉석해서 만드는 방식 / [캡쳐](매개변수){실행코드};
    }
}
 
void APlayerCharacterControl::InitFindWeaponMesh()
{
    SM_RifleWeapon = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("RifleWeaponMesh")); // 무기 소켓 추가
    SM_RifleWeapon->SetupAttachment(GetMesh());
    static ConstructorHelpers::FObjectFinder<UStaticMesh>rifleWeaponMesh(TEXT("/Script/Engine.StaticMesh'/Game/Asset/FPS_Weapon_Bundle/Weapons/Meshes/AR4/SM_AR4.SM_AR4'")); // 무기 SM 가져옴
    if (rifleWeaponMesh.Succeeded()) // SM 체크
    {
        SM_RifleWeapon->SetStaticMesh(rifleWeaponMesh.Object);
 
    }
    SM_RifleWeapon->AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform, TEXT("RifleWeapon_Socket")); // 소켓에 SM 장착
 
    SM_PistolWeapon = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("PistolWeaponMesh"));
    SM_PistolWeapon->SetupAttachment(GetMesh());
    static ConstructorHelpers::FObjectFinder<UStaticMesh> pistolweaponMesh(TEXT("/Script/Engine.StaticMesh'/Game/ATPS/Assets/Weapons/Pistol/Mesh/StaticMesh.StaticMesh'"));
    if (pistolweaponMesh.Succeeded())
    {
        SM_PistolWeapon->SetStaticMesh(pistolweaponMesh.Object);
    }
    SM_PistolWeapon->AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform, TEXT("PistolWeapon_Socket"));
}
 
void APlayerCharacterControl::InitIsWeaponMap()
{
    IsWeaponMap.Add(EWeaponType::Pistol, false); // 아이템 확인
    IsWeaponMap.Add(EWeaponType::SMG, false);
    IsWeaponMap.Add(EWeaponType::Rifle, false);
    WeaponCrosshairImageMap.Add(EWeaponType::Pistol, LoadObject<UTexture2D>(nullptr, TEXT("/Script/Engine.Texture2D'/Game/UMG/Texture/Crosshair.Crosshair'"))); // 맵 사용 시 반드시 add로 초기화 해줘야함
    WeaponCrosshairImageMap.Add(EWeaponType::SMG, LoadObject<UTexture2D>(nullptr, TEXT("")));
    WeaponCrosshairImageMap.Add(EWeaponType::Rifle, LoadObject<UTexture2D>(nullptr, TEXT("/Script/Engine.Texture2D'/Game/UMG/Texture/rifle_crosshair.rifle_crosshair'")));
    WeaponIconImageMap.Add(EWeaponType::Pistol, LoadObject<UTexture2D>(nullptr, TEXT("/Script/Engine.Texture2D'/Game/UMG/Texture/pistol.pistol'")));
    WeaponIconImageMap.Add(EWeaponType::SMG, LoadObject<UTexture2D>(nullptr, TEXT("/Script/Engine.Texture2D'/Game/UMG/Texture/smg.smg'")));
    WeaponIconImageMap.Add(EWeaponType::Rifle, LoadObject<UTexture2D>(nullptr, TEXT("/Script/Engine.Texture2D'/Game/UMG/Texture/rifle.rifle'")));
}
 
void APlayerCharacterControl::InitFindInput()
{
    static ConstructorHelpers::FObjectFinder<UInputMappingContext>InputContext(TEXT("/Script/EnhancedInput.InputMappingContext'/Game/Input/IMC_PlayerInput.IMC_PlayerInput'")); // IMC 지정
    if (InputContext.Object != nullptr)
    {
        DefaultContext = InputContext.Object;
    }
 
    static ConstructorHelpers::FObjectFinder<UInputAction>InputMove(TEXT("/Script/EnhancedInput.InputAction'/Game/Input/IA_Move.IA_Move'")); // IA_Move 지정
    if (InputMove.Object != nullptr)
    {
        MoveAction = InputMove.Object;
    }
 
    static ConstructorHelpers::FObjectFinder<UInputAction>InputLook(TEXT("/Script/EnhancedInput.InputAction'/Game/Input/IA_Look.IA_Look'")); // IA_Look 지정
    if (InputLook.Object != nullptr)
    {
        LookAction = InputLook.Object;
    }
 
    static ConstructorHelpers::FObjectFinder<UInputAction>InputAim(TEXT("/Script/EnhancedInput.InputAction'/Game/Input/IA_Aim.IA_Aim'")); // IA_Aim 지정; OnAim, OffAim 따로 지정해주지 않아도 됨
    if (InputAim.Object != nullptr)
    {
        AimAction = InputAim.Object;
    }
 
    static ConstructorHelpers::FObjectFinder<UInputAction>InputFire(TEXT("/Script/EnhancedInput.InputAction'/Game/Input/IA_Fire.IA_Fire'")); // IA_Fire 지정
    if (InputFire.Object != nullptr)
    {
        FireAction = InputFire.Object;
    }
 
    static ConstructorHelpers::FObjectFinder<UInputAction>InputOperate(TEXT("/Script/EnhancedInput.InputAction'/Game/Input/IA_Operate.IA_Operate'")); // IA_Operate 지정
    if (InputOperate.Object != nullptr)
    {
        OperateAction = InputOperate.Object;
    }
 
    static ConstructorHelpers::FObjectFinder<UInputAction>InputRifleChange(TEXT("/Script/EnhancedInput.InputAction'/Game/Input/IA_RifleChange.IA_RifleChange'")); // IA_RifleChange 지정
    if (InputRifleChange.Object != nullptr)
    {
        RifleChangeAction = InputRifleChange.Object;
    }
 
 
    static ConstructorHelpers::FObjectFinder<UInputAction>InputPistolChange(TEXT("/Script/EnhancedInput.InputAction'/Game/Input/IA_PistolChange.IA_PistolChange'")); // IA_PistolChange 지정
    if (InputPistolChange.Object != nullptr)
    {
        PistolChangeAction = InputPistolChange.Object;
    }
}
 
float APlayerCharacterControl::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
    const float Damage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser);
 
    GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Red, FString::Printf(TEXT("PlayerDamage : %f"), Damage));
 
    if (Damage > 0)
    {
        PlayerHP -= Damage; // HP 감소
        if (Damage >= 40 /*&& Montage 보유 확인*/// 강공격 피격 애니메이션
        {
            //GetMesh()->GetAnimInstance()->Montage_Play(); // 피격 애니메이션 재생
            UGameplayStatics::PlaySound2D(GetWorld(), HitSound); // 피격 소리 재생; 싱글 게임의 경우 2D, 멀티 게임의 경우 atLocation
        }
        else // 약공격 피격 애니메이션
        {
            UAnimInstance* animInstance = GetMesh()->GetAnimInstance();
            if (HitMontage.Num() > 0)
            {
                int randomInt = FMath::RandRange(0, HitMontage.Num() - 1);
                if (animInstance)
                {
                    animInstance->Montage_Play(HitMontage[randomInt]);
                }
            }
            //GetMesh()->GetAnimInstance()->Montage_Play();
            UGameplayStatics::PlaySound2D(GetWorld(), HitSound);
        }
        
        if (PlayerHP <= 0// HP = 0 확인
        {
            //GetMesh()->GetAnimInstance()->Montage_Play();
            // UI HP 강제로 0 설정
            return Damage;
        }
        if (HPTextBlock)
        {
            FText HP = FText::AsNumber(PlayerHP);
            HPTextBlock->SetText(HP);
            HPTextBlock->SetVisibility(ESlateVisibility::Visible);
        }
        
        FVector FXScale = FVector(111);
        PlayHitFX(GetActorLocation(), GetActorRotation(), FXScale);
        
        if (PlayerDamageShakeClass)
        {
            GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(PlayerDamageShakeClass); // Camera Shake 추가
        }        
    }
 
    return Damage;
}
 
void APlayerCharacterControl::PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale)
{
    if (HitFXArray.Num() > 0)
    {
        int32 RandomIndex = FMath::RandRange(0, HitFXArray.Num() - 1);
        UNiagaraSystem* SelectedFX = HitFXArray[RandomIndex];
 
        if (SelectedFX)
        {
            UNiagaraFunctionLibrary::SpawnSystemAtLocation(GetWorld(), SelectedFX, HitLocation);
        }
    }
 
    if (HitParticleSystemArray.Num() > 0)
    {
        int32 RandomIndex = FMath::RandRange(0, HitParticleSystemArray.Num() - 1);
        UParticleSystem* SelectedFX = HitParticleSystemArray[RandomIndex];
 
        if (SelectedFX)
        {
            UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), SelectedFX, HitLocation, HitRotator, FXScale);
        }
    }
}
 
void APlayerCharacterControl::InitFindWidget()
{
    if (HUDClass == nullptr)
    {
        HUDClass = LoadClass<UUserWidget>(nullptr, TEXT("/Game/UMG/WB_PlayerHUD.WB_PlayerHUD'_C"));
    }
    
    /*static ConstructorHelpers::FClassFinder<UUserWidget>HUD(TEXT("WidgetBlueprint'/Game/UMG/WB_PlayerHUD.WB_PlayerHUD'_C'"));
    
    if (HUD.Succeeded())
    {
        HUDClass = HUD.Class;
    }*/
}
cs

NormalZombie.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Fill out your copyright notice in the Description page of Project Settings.
 
#pragma once
 
#include "CoreMinimal.h"
#include "ZombieBase.h"
#include "BehaviorTree/BTTaskNode.h" // Task 노드에 대한 정보를 전달을 위해 추가
#include "NormalZombie.generated.h"
 
UENUM()
enum class EZombieAttackSoundType :uint8
{
    HumanZombieAttackSound1, HumanZombieAttackSound2, DogZombieAttackSound1, DogZombieAttackSound2, WingZombieAttackSound1, WingZombieAttackSound2
};
 
UCLASS()
class MYPROJECT_API ANormalZombie : public AZombieBase
{
    GENERATED_BODY()
 
public:
    ANormalZombie();
 
private:
    virtual void BeginPlay() override;
 
public:
    void InitAI();
    void PlayAttackSound();
    void PlayAttackMontage();
    
    void SetCurrentTask(UBTTaskNode* Task);
    UBTTaskNode* GetCurrentTask() const; // 외부로 현재 실행 중인 Task를 보내는 함수
 
private:
    UBTTaskNode* CurrentTask; // 현재 실행 중인 Task 정보를 저장
 
public:
    // AllowPrivateAccess: C++ 변수가 private로 선언되어도 접근 가능하게 허용 / MakeEditWidget: 에디터에서 이 변수를 3D 공간에 시각적으로 표시
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AI", meta= (AllowPrivateAccess = "true", MakeEditWidget = "true"))
    FVector ZombieMoveVector = FVector(000);
 
public:
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAttackSound")
    TMap<EZombieAttackSoundType, USoundBase*> ZombieAttackSounds;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAttackSound")
    TArray<USoundBase*>HumanZombieAttackSounds;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAttackSound")
    TArray<USoundBase*>DogZombieAttackSounds;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAttackSound")
    TArray<USoundBase*>WingZombieAttackSounds;
 
public:
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    TArray<UAnimMontage*>HumanZombieAttackMontages;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    TArray<UAnimMontage*>DogZombieAttackMontages;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    TArray<UAnimMontage*>WingZombieAttackMontages;
 
public:
    virtual float TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) override;
    virtual void PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale);
 
    UPROPERTY(EditAnywhere, Category = "Sound")
    USoundBase* ZombieHitSound;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    TArray<UAnimMontage*>ZombieHitMontage;
 
    //UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    //TArray<UAnimMontage*>HumanZombieHitMontage;
    
    //UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    //TArray<UAnimMontage*>DogZombieHitMontage;
    
    //UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ZombieAnim")
    //TArray<UAnimMontage*>WingZombieHitMontage;
 
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FX")
    TArray<UParticleSystem*> HitParticleSystemArray;
};
cs

NormalZombie.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Fill out your copyright notice in the Description page of Project Settings.
 
 
#include "NormalZombie.h"
#include "ZombieAnimInstance.h"
#include "AIController.h"
#include "ZombieAIController.h"
#include "Kismet/GameplayStatics.h"
#include "BehaviorTree/BehaviorTree.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "Animation/AnimInstance.h"
#include "Animation/AnimMontage.h"
 
ANormalZombie::ANormalZombie()
{
    InitAI();
}
 
void ANormalZombie::BeginPlay()
{
    Super::BeginPlay();
 
    AZombieAIController* AIController = Cast<AZombieAIController>(GetController());
    //if (AIController)
    //{
    //    UBlackboardComponent* BB = AIController->GetBlackboardComponent();
    //    if (BB)
    //    {
    //        FVector WorldMoveVector = GetActorTransform().TransformPosition(ZombieMoveVector); // 로컬 -> 월드 좌표로 변환 
    //        //FVector LocalMoveVector = GetActorTransform().TransformPosition(ZombieMoveVector); // 월드 -> 로컬 좌표로 변환
    //        //FVector WorldMoveVector = ZombieMoveVector; // 월드 좌표로 사용
    //        APawn* playerActor = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);
    //        BB->SetValueAsVector(TEXT("PlayerActor"), playerActor->GetActorLocation());
    //        BB->SetValueAsVector(TEXT("DefaultVector"), GetActorLocation());
    //        BB->SetValueAsVector(TEXT("RandomVector"), LocalMoveVector);
    //    }
    //}
}
 
void ANormalZombie::InitAI()
{
    AIControllerClass = AZombieAIController::StaticClass();
    AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned;
}
 
void ANormalZombie::PlayAttackSound()
{
    if (zombieType == EZombieType::HumanZombie && HumanZombieAttackSounds.Num() > 0// ZombieAttackSound가 있을 경우 실행
    {
        int randomInt = FMath::RandRange(0, HumanZombieAttackSounds.Num() - 1);
        UGameplayStatics::PlaySoundAtLocation(GetWorld(), HumanZombieAttackSounds[randomInt], GetActorLocation());
    }
    else if (zombieType == EZombieType::DogZombie && DogZombieAttackSounds.Num() > 0)
    {
        int randomInt = FMath::RandRange(0, DogZombieAttackSounds.Num() - 1);
        UGameplayStatics::PlaySoundAtLocation(GetWorld(), DogZombieAttackSounds[randomInt], GetActorLocation());        
    }
 
    else if (zombieType == EZombieType::WingZombie && WingZombieAttackSounds.Num() > 0)
    {
        int randomInt = FMath::RandRange(0, WingZombieAttackSounds.Num() - 1);
        UGameplayStatics::PlaySoundAtLocation(GetWorld(), WingZombieAttackSounds[randomInt], GetActorLocation());
    }    
}
 
void ANormalZombie::PlayAttackMontage()
{
    UAnimInstance* animInstance = GetMesh()->GetAnimInstance();
 
    if (zombieType == EZombieType::HumanZombie && HumanZombieAttackMontages.Num() > 0)
    {
        int randomInt = FMath::RandRange(0, HumanZombieAttackMontages.Num() - 1);
        if (animInstance)
        {
            animInstance->Montage_Play(HumanZombieAttackMontages[randomInt]);
        }
    }
    else if (zombieType == EZombieType::DogZombie && DogZombieAttackMontages.Num() > 0)
    {
        int randomInt = FMath::RandRange(0, DogZombieAttackMontages.Num() - 1);
        if (animInstance)
        {
            animInstance->Montage_Play(DogZombieAttackMontages[randomInt]);
        }
    }
 
    else if (zombieType == EZombieType::WingZombie && WingZombieAttackMontages.Num() > 0)
    {
        int randomInt = FMath::RandRange(0, WingZombieAttackMontages.Num() - 1);
        if (animInstance)
        {
            animInstance->Montage_Play(WingZombieAttackMontages[randomInt]);
        }
    }
}
 
void ANormalZombie::SetCurrentTask(UBTTaskNode* Task)
{
    CurrentTask = Task;
}
 
UBTTaskNode* ANormalZombie::GetCurrentTask() const
{
    return CurrentTask;
}
 
float ANormalZombie::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
    const float Damage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser);
 
    GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Blue, FString::Printf(TEXT("ZombieDamage : %f"), Damage));
 
    if (Damage > 0)
    {
        GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Blue, FString::Printf(TEXT("Damage Taken")));
        ZombieHP -= Damage;
 
        if (ZombieHitMontage.Num() > 0)
        {
            GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Blue, FString::Printf(TEXT("Damage")));
            UAnimInstance* animInstance = GetMesh()->GetAnimInstance();
            if (ZombieHitMontage.Num() > 0)
            {
                int randomInt = FMath::RandRange(0, ZombieHitMontage.Num() - 1);
                if (animInstance)
                {
                    GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Blue, FString::Printf(TEXT("Damage Anim")));
                    animInstance->Montage_Play(ZombieHitMontage[randomInt]);
                }
            }
            //GetMesh()->GetAnimInstance()->Montage_Play();
            UGameplayStatics::PlaySound2D(GetWorld(), ZombieHitSound);
        }
        //else // 약공격 피격 애니메이션
        //{
        //    GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Blue, FString::Printf(TEXT("Damage")));
        //    UAnimInstance* animInstance = GetMesh()->GetAnimInstance();
        //    if (ZombieHitMontage.Num() > 0)
        //    {
        //        int randomInt = FMath::RandRange(0, ZombieHitMontage.Num() - 1);
        //        if (animInstance)
        //        {
        //            GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Blue, FString::Printf(TEXT("Damage Anim")));
        //            animInstance->Montage_Play(ZombieHitMontage[randomInt]);
        //        }
        //    }
        //    //GetMesh()->GetAnimInstance()->Montage_Play();
        //    UGameplayStatics::PlaySound2D(GetWorld(), ZombieHitSound);
        //}
 
        if (ZombieHP <= 0)
        {
            //GetMesh()->GetAnimInstance()->Montage_Play();
            // UI HP 강제로 0 설정
            return Damage;
        }
 
        GEngine->AddOnScreenDebugMessage(-13.0f, FColor::Blue, FString::Printf(TEXT("ZombieHP : %f"), ZombieHP));
 
        FVector FXScale = FVector(111);
        PlayHitFX(GetActorLocation(), GetActorRotation(), FXScale);
    }
 
    return Damage;
}
 
void ANormalZombie::PlayHitFX(FVector HitLocation, FRotator HitRotator, FVector FXScale)
{
    if (HitParticleSystemArray.Num() > 0)
    {
        int32 RandomIndex = FMath::RandRange(0, HitParticleSystemArray.Num() - 1);
        UParticleSystem* SelectedFX = HitParticleSystemArray[RandomIndex];
 
        if (SelectedFX)
        {
            UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), SelectedFX, HitLocation, HitRotator, FXScale);
        }
    }
}
cs

BTTask_Attack.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Fill out your copyright notice in the Description page of Project Settings.
 
 
#include "BTTask_Attack.h"
#include "BehaviorTree/BTTaskNode.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "ZombieAIController.h"
#include "AIController.h"
#include "Kismet/GameplayStatics.h"
#include "NormalZombie.h"
#include "Engine/GameEngine.h"
#include "PlayerCharacterControl.h"
#include "Engine/DamageEvents.h"
 
UBTTask_Attack::UBTTask_Attack()
{
    NodeName = "ZombieAttackTask";
    bNotifyTick = false;
}
 
 
EBTNodeResult::Type UBTTask_Attack::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
    Super::ExecuteTask(OwnerComp, NodeMemory);
 
    ANormalZombie* zombie = Cast<ANormalZombie>(OwnerComp.GetAIOwner()->GetCharacter());
 
    if (zombie == nullptr)
    {
        return EBTNodeResult::Failed;
    }
 
    zombie->SetCurrentTask(this);
    zombie->PlayAttackSound(); // 공격 소리 재생
    zombie->PlayAttackMontage(); // 공격 애니메이션 재생
 
    return EBTNodeResult::Succeeded;
}
 
void UBTTask_Attack::AttackTrace(ANormalZombie* NormalZombie) // 공격 Collision 생성
{
    if (!NormalZombie) return;
 
    FVector RightHand = NormalZombie->GetMesh()->GetSocketLocation("hand_r");
    FVector LeftHand = NormalZombie->GetMesh()->GetSocketLocation("hand_l");
        
    float SphereRadius = 50.0f;
    float ZombieDamage = 0.0f;
 
    if (NormalZombie->zombieType == EZombieType::HumanZombie)
    {
        SphereRadius = 100.0f;
        ZombieDamage = 5;
    }
 
    else if (NormalZombie->zombieType == EZombieType::DogZombie)
    {
        SphereRadius = 100.0f;
        ZombieDamage = 10;
    }
 
    else if (NormalZombie->zombieType == EZombieType::WingZombie)
    {
        SphereRadius = 100.0f;
        ZombieDamage = 50;
    }
 
    FHitResult Hit;
    FCollisionQueryParams Params;
    Params.AddIgnoredActor(NormalZombie);
 
    bool isHit = GetWorld()->SweepSingleByChannel(Hit, RightHand, LeftHand, FQuat::Identity, ECC_GameTraceChannel4, FCollisionShape::MakeSphere(SphereRadius), Params);
    DrawDebugSphere(GetWorld(), RightHand, SphereRadius, 12, FColor::Red, false1.0f);
    DrawDebugSphere(GetWorld(), LeftHand, SphereRadius, 12, FColor::Red, false1.0f);
 
    if (isHit)
    {
        APlayerCharacterControl* Player = Cast<APlayerCharacterControl>(Hit.GetActor());
        if (Player)
        {
            //Player->TakeDamage(Damage, FDamageEvent(), NormalZombie->GetController(), NormalZombie);
            UGameplayStatics::ApplyDamage(Player, ZombieDamage, Player->GetInstigatorController(), Player, NULL);
        }
    }
}
cs