Post

UE 使用 Spline 实现点画线

方法

1
2
3
4
5
UPROPERTY()  
USplineComponent* SplineComponent;

UPROPERTY(BlueprintReadWrite, EditAnywhere)  
UStaticMesh* LineMesh;
1
2
3
4
5
6
7
void ASomeActor::BeginPlay()  
{  
    Super::BeginPlay();
    // 需要在蓝图中添加Spline组件
    SplineComponent = Cast<USplineComponent>(this->GetComponentByClass(
	    USplineComponent::StaticClass()));  
}
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
void ASomeActor::DrawSomeLine()  
{  
    TArray<FVector> Vertexes = {};

	// Fill Vertexes
  
    for (auto i = 0; i < Vertexes.Num(); i++)  
    {  
       SplineComponent->AddSplinePoint(
	       Vertexes[i], ESplineCoordinateSpace::World, false);  
    }  
  
    for (auto i = 0; i <= SplineComponent->GetNumberOfSplinePoints() - 1; ++i)  
    {  
       const auto SplineMesh = NewObject<USplineMeshComponent>(this);  
       SplineMesh->RegisterComponent();  
       SplineMesh->SetMobility(EComponentMobility::Movable);  
       SplineMesh->SetStaticMesh(LineMesh);
       SplineMesh->SetForwardAxis(ESplineMeshAxis::Z);  
  
       const FVector& StartLocation = 
	       SplineComponent->GetLocationAtSplinePoint(i, ESplineCoordinateSpace::World);
       const FVector& StartTangent = 
	       SplineComponent->GetTangentAtSplinePoint(i, ESplineCoordinateSpace::World);  
       const FVector& EndLocation = 
	       SplineComponent->GetLocationAtSplinePoint((i + 1) % 
	       SplineComponent->GetNumberOfSplinePoints(), 
	       ESplineCoordinateSpace::World);  
       const FVector& EndTangent = SplineComponent->GetTangentAtSplinePoint((i + 1) % 
	       SplineComponent->GetNumberOfSplinePoints(), 
	       ESplineCoordinateSpace::World);  
	       
       SplineMesh->SetStartAndEnd(StartLocation, StartTangent, 
	       EndLocation, EndTangent);  
    }  
}

原理

使用SplineComponent画线,由于SplineComponent画出的线仅在Debug时可见,在每两个点之间添加SplineMesh,SplineMesh长度可随意,Spline会自动进行延伸

This post is licensed under CC BY 4.0 by the author.