오늘부터는 충돌과 오버랩 이벤트에 대해서 알아보자
모든 충돌이 가능한 객체는 충돌 섹션이 있다. 그리고 오늘 여기서 주의 깊게 볼 것은 콜리전 프리셋이다.
콜리전 프리셋은 많은 선택지를 가지고 있는데 이를 통해 해당 구성요소에 대한 충돌 시의 행동을 결정한다.
콜리선 반응에 대한 자세한 설정은 밑의 사진을 보면 알 수 있는데
각 선택지마다 밑의 선택지의 체크가 달라지고 이에 따라 다양한 콜리전 시의 행동을 할 수 있다.
만약 콜리전 활성화됨을 no collision으로 하게 되면 물체를 통과하게 된다.
이제 오버랩이벤트를 한번 보자
일단 아이템에 플레이어와 충돌했을 때 이벤트가 발생하도록 오버랩을 수정해주자
그렇게하고 이벤트를 설정해주게 되면 아래 사진과 같은 결과가 나온다.
OnComponentBeginOverlap 이벤트는 특정 콜리전 컴포넌트가 다른 콜리전 컴포넌트와 충돌하거나 겹쳐지기 시작할 때 발생하는 이벤트로 주로 충돌을 감지하고, 이에 대한 반응을 프로그래밍하는 데 사용한다.
이것을 코드로 구현해보자
일단 콜리션 구 변수를 선언해주고 초기화 해주자
Item.h
class USphereComponent;
UPROPERTY(VisibleAnywhere)
USphereComponent* Sphere;
Item.cpp
#include "Components/SphereComponent.h"
Sphere = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere"));
Sphere->SetupAttachment(GetRootComponent());
그리고 오버랩이벤트를 감지했을 때 작동할 Delegate에 바인딩할 콜백함수를 정의해주자
Item.h
UFUNCTION()
void OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
// Called when the game starts or when spawned
void AItem::BeginPlay()
{
Super::BeginPlay();
Sphere->OnComponentBeginOverlap.AddDynamic(this, &AItem::OnSphereOverlap);
}
void AItem::OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
const FString OtherActorName = OtherActor->GetName();
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(1, 30.f, FColor::Blue, OtherActorName);
}
}
결과
마지막으로 콜리션에서 빠져나올 때 이벤트가 실행되는 OnSphereEndOverlap을 구현해보자
일단 헤더파일에 콜백함수를 만들어주고 cpp코드의 BeginPlay에서 Delegate와 바인딩시켜준 뒤 원하는 기능을 콜백 함수
에 붙여주면 된다.
중요한 점은 리플렉션 시스템에 이용할 수 있도록 함수는 UFUNCTION()매크로 함수를 붙여주어야한다는 것이다.
Item.h
UFUNCTION()
void OnSphereEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
Item.cpp
void AItem::BeginPlay()
{
Super::BeginPlay();
Sphere->OnComponentBeginOverlap.AddDynamic(this, &AItem::OnSphereOverlap);
Sphere->OnComponentEndOverlap.AddDynamic(this, &AItem::OnSphereEndOverlap);
}
void AItem::OnSphereEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
const FString OtherActorName = FString("Ending Overlap with : ") + OtherActor->GetName();
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(1, 30.f, FColor::Red, OtherActorName);
}
}
결과
'게임공부 > Unreal Engine' 카테고리의 다른 글
[Unreal Engine][C++]11. Attacking (1) | 2024.08.04 |
---|---|
[Unreal Engine][C++]10. The Weapon Class (0) | 2024.07.29 |
[Unreal Engine][C++]8. Animation (1) | 2024.07.22 |
[Unreal Engine][C++]7. Character Class (0) | 2024.07.18 |
[Unreal Engine][C++]6.움직이기 (1) | 2024.07.16 |