Hello everyone,
I am trying to make a Weapon & Inventory system and while I was trying to make a simple Pick Up function for weapons I faced this issue. What I am trying to do is to trace a line and then get the actor instance that the line hit and then cast my item class from that to pick it up, I use the following code to achieve this.
AActor* AMPCharacter::GetActorInView()
{
FVector CamLocation;
FRotator CamRotation;
if (Controller == NULL)
{
#ifdef DEBUG_MODE
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Red, TEXT("FATAL ERROR FAILED TO ACCESS CONTROLLER"));
#endif
return NULL;
}
Controller->GetPlayerViewPoint(CamLocation, CamRotation);
const FVector TraceStart = CamLocation;
const FVector Direction = CamRotation.Vector();
const FVector TraceEnd = TraceStart + (Direction * MaxUseDistance);
FCollisionQueryParams TraceParams(FName(TEXT("TraceActor")), true, this);
TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = false;
TraceParams.bTraceComplex = true;
FHitResult Hit(ForceInit);
GetWorld()->LineTraceSingleByChannel(Hit, TraceStart, TraceEnd, ECC_PhysicsBody, TraceParams);
#ifdef DEBUG_MODE
DrawDebugLine(GetWorld(), TraceStart, TraceEnd, FColor::Red, false, 1.0f);
#endif
return Hit.GetActor();
}
and then to utilize this I simply use
AActor* ActorInView = GetActorInView();
if (ActorInView)
{
#ifdef DEBUG_MODE
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Red, TEXT("There is an Actor in view!"));
#endif
AItem* Item = Cast<AItem>(ActorInView);
if (ActorInView->IsA(AItem::StaticClass()) && Item)
{
#ifdef DEBUG_MODE
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Red, TEXT("It's an Item!"));
#endif
PickUpItem(Item);
}
}
However, even though I can see the line hitting the weapon in game, this line of code " AActor* ActorInView = GetActorInView();" always returns NULL. Can anyone tell me what I am doing wrong?
Any help will be appreciated,
Thanks.