- 출발지 - 목적지를 순회하는 플랫폼 만들기 실습
- 타겟 위치를 에디터에서 편리하게 설정하는 방법
- Local → World 좌표 변환 방법
- 움직이는 액터 만들기
- 목적지를 Editor에서 편하게 설정하도록 변수 선언 및 설정하기
private:
UPROPERTY(EditAnywhere, Category = "Option", meta = (AllowPrivateAccess = "true"), meta = (MakeEditWidget = true))
FVector TargetLocation;

- 이동 로직 만들기
출발지에서 목적지로 이동한다는 것은 벡터로 표현이 가능합니다.
→ 목적 위치(벡터) - 출발 위치(벡터)
속도를 저장할 변수를 선언합니다.
private:
UPROPERTY(EditAnywhere, Category = "Option", meta = (AllowPrivateAccess = "true"))
int32 Speed;
이동한다는 것은 매 프레임 현재 위치에서 속도만큼 이동한다는 것을 의미합니다.
→ 내 위치 = 현재위치 + 속도
위와 같은 방법은 하나의 단점이 존재합니다.
매 프레임마다 이동하므로 컴퓨터 성능에 따라 액터의 이동속도가 변할 수 있습니다.
즉, 1초에 1프레임을 호출 가능한 성능의 컴퓨터와 1초에 10프레임을 호출 가능한 성능의 컴퓨터 간의 차이가 10배의 속도 차이로 이어진다는 것을 의미합니다.
다음 프레임이 오기까지의 시간을 체크해 반영해줘야 합니다.
→ 내 위치 = 현재위치 + 속도 * DeltaTime
void AMovingPlatforms::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// 현재 액터의 위치를 저장합니다.
FVector Location = GetActorLocation();
// 속도만큼 이동시켜줍니다.
Location += Speed * DeltaTime;
// 이동한 위치를 저장합니다.
SetActorLocation(Location);
}
- 이동 방향 구하기
// 방향 구하기
FVector Direction = (TargetLocation - Location).GetSafeNormal();
// 특정 방향으로 속도만큼 이동시켜줍니다.
Location += Direction * Speed * DeltaTime;
// 이동한 위치를 저장합니다.
SetActorLocation(Location);
현재 상황에서 실행해보면?
- 액터는 타겟 위치를 넘어서서 이동합니다.
- 타겟 위치는 액터에 포함되어 있습니다. (타겟 위치의 부모 : 액터)
- 즉, 액터가 움직이면 포함된 자식(타겟 위치)도 같이 움직이기 때문에 타겟 위치가 계속 업데이트 되며 원하는 위치에서 종료되지 않습니다.
- 시작 위치와 종료 위치를 시작과 동시에 저장하고 반영하기
// MovingPlatforms.h
private:
FVector GlobalTargetLocation;
FVector GlobalStartLocation;
// MovingPlatforms.cpp
void AMovingPlatforms::BeginPlay()
{
Super::BeginPlay();
// 시작 지점과 목표 지점(World) 설정
GlobalStartLocation = GetActorLocation();
GlobalTargetLocation = GetTransform().TransformPosition(TargetLocation);
}
void AMovingPlatforms::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
FVector Location = GetActorLocation();
// 방향 설정
FVector Direction = (GlobalTargetLocation - GlobalStartLocation).GetSafeNormal();
Location += Direction * Speed * DeltaTime;
SetActorLocation(Location);
}
- 구간 반복 이동 설정하기
void AMovingPlatforms::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
FVector Location = GetActorLocation();
// 거리를 구해 목적지를 지나간다면?
if ((Location - GlobalStartLocation).Size() > (GlobalTargetLocation - GlobalStartLocation).Size())
{
// 출발지, 목적지 교체
FVector Temp = GlobalTargetLocation;
GlobalTargetLocation = GlobalStartLocation;
GlobalStartLocation = Temp;
}
// 방향 구하기
FVector Direction = (GlobalTargetLocation - GlobalStartLocation).GetSafeNormal();
// 해당 방향으로 이동시키기
Location += Direction * Speed * DeltaTime;
SetActorLocation(Location);
}
