Hi everyone !
I am trying to create a weapon system in UE4 in C++. So I have a Weapon class which is supposed to trace a line from the muzzle of the weapon skeletal mesh muzzle socket, to the first actor it meet. This is why I use the LineTraceSingle function. But, it doesn’t work ! When I shoot in game, it always do like if it never meet an actor : Hit.EndTrace is always (0,0,0), and the function return also a false boolean. Here is a part of my source file :
void AWeapon::TraceToAim()
{
GEngine->AddOnScreenDebugMessage(-1, .5f, FColor::Red, TEXT("shoot"));
// Calculate the start and the end of the trace (everything works here)
const int32 RandomSeed = FMath::Rand();
FRandomStream WeaponRandomStream(RandomSeed);
const float CurrentSpread = WeaponData.WeaponSpread;
const float SpreadCone = FMath::DegreesToRadians(CurrentSpread * 0.5);
const FVector AimDir = Mesh->GetSocketRotation("MuzzleSocket").Vector();
const FVector StartTrace = Mesh->GetSocketLocation("MuzzleSocket");
const FVector ShootDir = WeaponRandomStream.VRandCone(AimDir, SpreadCone, SpreadCone);
const FVector EndTrace = StartTrace + ShootDir * WeaponData.WeaponRange;
// Actors to ignore
TArray<AActor*> ActorsToIgnore;
ActorsToIgnore.Add(Instigator);
ActorsToIgnore.Add(this);
if (isHandle && WeaponOwner != NULL)
{
ActorsToIgnore.Add(WeaponOwner);
}
FHitResult Hit(ForceInit);
bool success = Trace(ActorsToIgnore, StartTrace, EndTrace, Hit);
UE_LOG(LogTemp, Warning, TEXT("Cone direction : %s ;Maximal shooting location : %s ;Hit objective : %s"), *AimDir.ToString(), *EndTrace.ToString(), *Hit.TraceEnd.ToString());
if (!success)
{
Hit.TraceEnd = EndTrace;
UE_LOG(LogTemp, Warning, TEXT("Fail"));
}
else
UE_LOG(LogTemp, Warning, TEXT("Success !"));
// Fire
DrawDebugLine(this->GetWorld(), StartTrace, Hit.TraceEnd, FColor::Black, true, 10000.f, 10.f);
}
bool AWeapon::Trace(
TArray<AActor*>& ActorsToIgnore,
const FVector& Start,
const FVector& End,
FHitResult& HitOut,
ECollisionChannel CollisionChannel,
bool ReturnPhysMat)
{
if (ActorsToIgnore.Num() <= 0) return false;
if (ActorsToIgnore[0] == NULL) return false;
FCollisionQueryParams TraceParams(FName(TEXT("Weapon Trace")), true, ActorsToIgnore[0]);
TraceParams.bTraceComplex = true;
//TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = ReturnPhysMat;
//Ignore Actors
TraceParams.AddIgnoredActors(ActorsToIgnore);
//Re-initialize hit info
HitOut = FHitResult(ForceInit);
ActorsToIgnore[0]->GetWorld()->LineTraceSingle(
HitOut, //result
Start, //start
End, //end
CollisionChannel, //collision channel
TraceParams);
return (HitOut.GetActor() != NULL);
}
And here is my log when I shoot :
I hope you will be able to help me !
Thank you !