Simple Raycast (Line Trace) from camera.

Hi all, I’m new to Unreal Engine 4 and I’m trying to figure out the equivalent of Unity’s Raycast. I have run into ActorLineTraceSingle, which seems to have similar parameters, but I can’t wrap my head around how to implement this, and I’m unable to find a solid example anywhere. Can someone give a an example of the simplest Line Trace implementation, say, how to cast from camera and debug what object I’m looking or aiming at? Any small c++ example or a point in the right direction will be greatly appreciated, thank you in advance.

There’s a simple Line Trace here - Victor's Use System[Tutorial] - Community & Industry Discussion - Epic Developer Community Forums

Here’s my implementation of it:

bool ClassName::DoTrace(FHitResult* RV_Hit, FCollisionQueryParams* RV_TraceParams)
{
	if (Controller == NULL) // access the controller, make sure we have one
	{
		return false;
	}

	// get the camera transform
	FVector CameraLoc;
	FRotator CameraRot;
	GetActorEyesViewPoint(CameraLoc, CameraRot);

	FVector Start = CameraLoc;
    // you need to add a uproperty to the header file for a float PlayerInteractionDistance
	FVector End = CameraLoc + (CameraRot.Vector() * PlayerInteractionDistance);

	RV_TraceParams->bTraceComplex = true;
	RV_TraceParams->bTraceAsyncScene = true;
	RV_TraceParams->bReturnPhysicalMaterial = true;

	//  do the line trace
	bool DidTrace = GetWorld()->LineTraceSingle(
		*RV_Hit,		//result
		Start,		//start
		End,		//end
		ECC_Pawn,	//collision channel
		*RV_TraceParams
		);

	return DidTrace;
}

Call it like this:

FHitResult RV_Hit(ForceInit);
FCollisionQueryParams RV_TraceParams = FCollisionQueryParams(FName(TEXT("RV_Trace")), true, this);
DoTrace(&RV_Hit, &RV_TraceParams);

And if you want the trace to ignore an actor (pretend it’s not there) you can do this before you pass it to the trace (you can do this multiple times for multiple actors, but this might not be efficient):

RV_TraceParams.AddIgnoredActor(ActorThingy);

You can also fiddle around with the trace parameters to change what the trace will and won’t hit on. I’ll leave the exercise to the viewer.

The result will end up in you RV_Hit, which will contain all the information about what you hit. FHitResult | Unreal Engine Documentation

Thanks a ton for this very informative reply! I’ll look into it and hopefully knock it out by the end of the night!

:smiley:

I would suggests sending in the parameters as references instead, and probably the query params as const & since the trace should not change them just read.