How to get terrain height at X and Y coordinates in C++?

Hi , does anyone know how to get the z value for terrain at a particular x and y world coordinate using c++?

I could look at the height map itself to calculate heights, but all that would give me is a height of a peaks and troughs, rather than at some point in between them, which is what I’m after.

Googling around it would seem that a line trace may be the answer I am looking for, but I can’t find any C++ examples of this, or even anything similar that I could adapt for my purpose.

Ultimately I want to use C++ to align spline meshes to terrain. An easy job, if I can just get a terrain Z values whilst I’m getting the x,y location values along a spline.

This is a simple example of an AActor method, you can search about LineTrace methods. Hope it helps.

Header File

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"

UCLASS()
class MYPROJECT_API AMyActor : public AActor
{
	GENERATED_BODY()
	
public:
	UFUNCTION(BlueprintPure, meta = ( AdvancedDisplay = "bDrawDebugLines" ))
		float GetSurface(FVector2D Point, bool bDrawDebugLines = false);
};

Cpp

#include "MyActor.h"

#include "Runtime/Engine/Classes/Engine/EngineTypes.h"
#include "Runtime/Engine/Classes/Engine/World.h"
#include "Runtime/Engine/Public/DrawDebugHelpers.h"

float AMyActor::GetSurface(FVector2D Point, bool bDrawDebugLines)
{
	UWorld* World{ this->GetWorld() };

	if (World)
	{
		FVector StartLocation{ Point.X, Point.Y, 1000 };	// Raytrace starting point.
		FVector EndLocation{ Point.X, Point.Y, 0 };			// Raytrace end point.

		// Raytrace for overlapping actors.
		FHitResult HitResult;
		World->LineTraceSingleByObjectType(
			OUT HitResult,
			StartLocation,
			EndLocation,
			FCollisionObjectQueryParams(ECollisionChannel::ECC_WorldStatic),
			FCollisionQueryParams()
		);

		// Draw debug line.
		if (bDrawDebugLines)
		{
			FColor LineColor;

			if (HitResult.GetActor()) LineColor = FColor::Red;
			else LineColor = FColor::Green;

			DrawDebugLine(
				World,
				StartLocation,
				EndLocation,
				LineColor,
				true,
				5.f,
				0.f,
				10.f
			);
		}

		// Return Z location.
		if (HitResult.GetActor()) return HitResult.ImpactPoint.Z;
	}

	return 0;
}

Blueprint

Thanks Newest, that’s extremely helpful, I can use the X and Y from getdiatancealongspline at increments and just set my start and end locations as well above and below my terrain. Happy days :slight_smile: