I’m trying to draw a line trace that starts at camera position for my third person character, basically I want to replicate this following blueprint but in C++ :
This has proven harder to do because I started off with a BluePrint project. I tried to get Camera Location and Rotation with PlayerCameraManager, but it says it’s undefined
Here’s my code :
// Fill out your copyright notice in the Description page of Project Settings.
#include "GameFramework/PlayerController.h"
#include "Engine/World.h"
#include "DrawDebugHelpers.h"
#include "Camera/PlayerCameraManager.h"
#include "GrabObjects.h"
#include "CollisionQueryParams.h"
#define OUT
// Sets default values for this component's properties
UGrabObjects::UGrabObjects()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UGrabObjects::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void UGrabObjects::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
FVector PlayerViewPointLocation;
FRotator PlayerViewPointRotation;
// PlayerCameraManager PROBLEM
// Get player viewport
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(
OUT PlayerViewPointLocation,
OUT PlayerViewPointRotation
);
// Draw a line from player showing reach
// PlayerViewPointRotation.Vector() is the unit vector
FVector LineTraceEnd = PlayerViewPointLocation + PlayerViewPointRotation.Vector() * Reach;
DrawDebugLine(
GetWorld(),
PlayerViewPointLocation,
LineTraceEnd,
FColor(0, 255, 0),
0.f,
0,
5.f
);
// Ray-cast out to a certain distance (Reach)
FHitResult Hit;
// -> False for complexe collisions and GetOwner() to ignore
FCollisionQueryParams TraceParams(FName(TEXT("")), false, GetOwner());
GetWorld()->LineTraceSingleByObjectType(
OUT Hit,
PlayerViewPointLocation,
LineTraceEnd,
FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
TraceParams
);
// -> See what it hits
AActor* ActorHit = Hit.GetActor();
if (ActorHit) {
UE_LOG(LogTemp, Error, TEXT("Line trace has hit: %s"), *(ActorHit->GetName()))
}
}