Second LineTrace based on first LineTrace

I’m trying to get get a line trace from the character’s weapon to the impact point of the prior line trace which came from the camera:

void APlayerCharacter::PerformCameraLineTrance()
{
	if (APlayerController* playerController = Cast<APlayerController>(GetController()))
	{
		if (followCamera)
		{

			// Get camera location and forward vector
			FVector startTrace = followCamera->GetComponentLocation();
			FVector forwardVector = followCamera->GetForwardVector();
			FVector endTrace = startTrace + forwardVector * 5000.0f;

			// weapon muzzle location
			FVector muzzleStartTrace = equippedWeapon->GetMuzzleTransform().GetLocation();

			FHitResult hitResult;
			FHitResult weaponHitResult;

			// Ignore the character itself
			FCollisionQueryParams collisionParams;
			collisionParams.AddIgnoredActor(this);
			collisionParams.AddIgnoredActor(equippedWeapon);



			// Perform the line trace from Camera
			if (GetWorld()->LineTraceSingleByChannel(hitResult, startTrace, endTrace, ECC_Visibility, collisionParams))
			{
				GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Cyan, FString::Printf(TEXT("Camera hit")));
			}
			else
			{
				GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Orange, FString::Printf(TEXT("Camera hit false")));
			}

			// Perform the line trace from weapon
			if (GetWorld()->LineTraceSingleByChannel(weaponHitResult, muzzleStartTrace, hitResult.ImpactPoint, ECC_Visibility, collisionParams))
			{
				DrawDebugBox(GetWorld(), hitResult.ImpactPoint, FVector(5, 5, 5), FColor::Emerald, false, 2.0f);
				GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Green, FString::Printf(TEXT("Weapon hit")));
			}
			else
			{
				GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::Printf(TEXT("Weapon hit false")));
			}

			// Draw a debug line for visualization
			DrawDebugLine(GetWorld(), muzzleStartTrace, hitResult.ImpactPoint, FColor::Red,
				false, // persistent
				2.0f, // life time
				2.0f, // thickness
				5.0f  // depth bias
			);

			// Draw a debug line for visualization
			DrawDebugLine(GetWorld(), startTrace, endTrace, FColor::Blue,
				false, // persistent
				2.0f, // life time
				2.0f, // thickness
				5.0f  // depth bias
			);
		}
	}
}

Problem is, the second line trace works…sometimes. But most of the time it fails.

The idea is to avoid that the player can shoot “around corners” with a second line trace from the player weapon. Any ideas?

Turns out the second line trace just wasn’t long enough even though it was supposed to be between predefined points.

Solution:

// Perform the line trace from weapon
if (GetWorld()->LineTraceSingleByChannel(weaponHitResult, muzzleStartTrace, hitResult.ImpactPoint + forwardVector * 0.01f, ECC_Visibility, collisionParams))
´´´

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.