본문 바로가기

강동새싹언리얼수업/언리얼

231211 Design Pattern - 컴포넌트

https://ittrue.tistory.com/90

 

[Git / Github] 포크 (Fork) 하는 방법 (오픈 소스 프로젝트 복제하기)

Fork란? 오픈 소스 프로젝트를 공부하거나 Contributors가 되고 싶을 때, 해당 원격 저장소(Remote Repository)를 자신의 원격 저장소로 복사할 수 있다. 이를 Fork라 한다. 깃허브의 경우 공개된 모든 자료

ittrue.tistory.com

 

InventoryComp 이름.

  • 컴포넌트 기반 패턴 (Component-based Pattern):  [Unreal 한정]
  • 팩토리 메서드 패턴 (Factory Method Pattern):
  • 옵저버 패턴 (Observer Pattern):
  • 프록시 패턴 (Proxy Pattern):
  • 커맨드 패턴 (Command Pattern):
  • 프로토타입 패턴 (Prototype Pattern):
  • 각 컴포넌트는 특정한 기능을 수행하는 독립적인 단위로 분리
  • 컴포넌트들은 게임 오브젝트에 추가되어 조합

다양한 컴포넌트들을 조합하여 하나의 게임 오브젝트를 만들어내며,
이를 통해 유연하고 재사용 가능한 코드를 작성 가능

 

 

 

LineTraceDetector.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "LineTraceDetector.generated.h"


UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class THIRDPERSONTEMPLATE_API ULineTraceDetector : public UActorComponent
{
	GENERATED_BODY()

public:
	// Sets default values for this component's properties
	ULineTraceDetector();

protected:
	// Called when the game starts
	virtual void BeginPlay() override;

public:
	// Called every frame
	virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;


	UFUNCTION(BlueprintCallable)
	FHitResult PerformLineTrace();

private:
	UPROPERTY(EditAnywhere)
	float TraceDistance = 1000.0f; // 라인 트레이스 거리

	UPROPERTY(EditAnywhere)
	TSubclassOf<AActor> ActorClassToTrace; // 찾고자 하는 액터 클래스

	UFUNCTION()
	void OnLineTraceHit(FHitResult HitResult);

};

LineTraceDetector.cpp

// Fill out your copyright notice in the Description page of Project Settings.


#include "LineTraceDetector.h"
#include "DrawDebugHelpers.h"


// Sets default values for this component's properties
ULineTraceDetector::ULineTraceDetector()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	PrimaryComponentTick.bCanEverTick = true;

	// ...
}


// Called when the game starts
void ULineTraceDetector::BeginPlay()
{
	Super::BeginPlay();

	// ...
	
}


// Called every frame
void ULineTraceDetector::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	// ...
}

FHitResult ULineTraceDetector::PerformLineTrace()
{
    FVector StartLocation = GetOwner()->GetActorLocation();
    FVector EndLocation = StartLocation + GetOwner()->GetActorForwardVector() * TraceDistance;

    FHitResult HitResult;
    FCollisionQueryParams CollisionParams;
    CollisionParams.AddIgnoredActor(GetOwner());

    // 라인 트레이스 수행
    bool bHit = GetWorld()->LineTraceSingleByChannel(
        HitResult,
        StartLocation,
        EndLocation,
        ECollisionChannel::ECC_Visibility,
        CollisionParams
    );

    if (bHit)
    {
        // 라인 트레이스가 충돌한 경우
        OnLineTraceHit(HitResult);
    }
    return HitResult;
}

void ULineTraceDetector::OnLineTraceHit(FHitResult HitResult)
{
    if (HitResult.GetActor() && HitResult.GetActor()->IsA(ActorClassToTrace))
    {
        // 원하는 클래스의 액터를 찾은 경우
        AActor* FoundActor = HitResult.GetActor();
        // 여기서 원하는 작업을 수행하거나 해당 액터를 사용할 수 있습니다.
        if (FoundActor)
        {
            GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Green, (TEXT("%s"), *FoundActor->GetName()));
        }
    }
}

 

   TPSPlayer blueprint에 추가

 

 

  • 객체 생성 추상화: 클라이언트 코드는 객체를 생성하는 구체적인 클래스를 알 필요 없이 추상화된 팩토리 메서드를 호출하여 객체를 생성할 수 있습니다. 예를 들어, CreateEnemy() 함수를 호출하여 Enemy의 구체적인 서브 클래스(예: Goblin)를 생성할 수 있습니다.
  •  
  • 확장성 및 유연성: 새로운 유닛이나 적 종류를 추가(신규 콘텐츠 추가)할 때 기존 코드를 수정하지 않고 새로운 클래스를 추가하여 확장할 수 있습니다. 예를 들어, 새로운 적(예: Orc)을 추가하려면 Orc 클래스를 만들고 AEnemy를 상속하여 구현만 하면 됩니다.
  •  
  • 객체 간의 결합도 감소: 유닛 및 적 클래스들은 서로 느슨하게 연결되어 있어, 변경사항이 다른 클래스에 미치는 영향을 최소화합니다. 이로써 유지보수가 용이해집니다.
  •  
  • 다형성 및 오버라이딩 활용: 추상 클래스와 가상 함수를 통해 다형성을 활용할 수 있으며, 서브 클래스에서 오버라이딩하여 각 클래스의 특징에 맞게 구현할 수 있습니다.

 

'강동새싹언리얼수업 > 언리얼' 카테고리의 다른 글

231212 Observer  (0) 2023.12.12
231212 수업 Interface  (0) 2023.12.12
시계만들기  (0) 2023.12.04
수업  (0) 2023.12.04
231130 수업 플레이어 Widget  (0) 2023.11.30