I would like to know if it is possible to get the material properties (i.e.: metalicity, roughness, diffuse constants, ambiant lighting, specular constants, etc.) from a FHitResult object returned by a ray cast call. And if possible how to do it? I tried using:
// inside some class here
FCollisionQueryParams TraceParams = FCollisionQueryParams(FName(TEXT("Laser_Trace")), true, this);
TraceParams.bTraceComplex = true;
TraceParams.bReturnPhysicalMaterial = false;
FHitResult HitInfo(ForceInit);
// the following call works well and returns a correct HitInfo
GetWorld()->ParallelLineTraceSingleByChannel(
HitInfo,
Begin,
End,
ECC_GameTraceChannel2,
TraceParams,
FCollisionResponseParams::DefaultResponseParam
);
// now to get material properties
auto * comp = HitInfo.GetComponent();
int32 sectionIndex = 0;
int32 faceIndex = HitInfo.FaceIndex;
// this usually segfaults or returns nullptr
UMaterialInterface * materialInterface = comp->GetMaterialFromCollisionFaceIndex(faceIndex, sectionIndex);
// I also tried this
UMaterial * material = comp->GetMaterial(0)->GetMaterial();
FScalarMaterialInput metallic = materialInterface->GetMaterial()->Metallic;
nothing I tried worked so far. Sometimes it segfaults, but most of the times everything I get is a nullptr.
Hey @fgoud. I believe your problem is that you are trying to access the material info from the component that you are hitting with the raycast. You don’t really know what component you may hit, it will probably be a collision component. What you need to do is from the component access the Owner and then get the static mesh or cast the received component to a UStaticMeshComponent and then try to access its materials (if it is not nullptr). Once you are sure you have the static mesh then you can get the materials from it. Right now it probably crashes because you are trying to get a material from a component that doesn’t have any and then when you try to use that material (that most likely is a nullptr) then you get a crash. It may also be that even when you hit a StaticMeshComponent, you may still not have a valid FaceIndex value from the raycast result, so passing that to a function to get a material will give you a nullptr even if that component has materials.
Actually, I managed to get a UStaticMeshComponent. Then, from it do comp->GetMaterialFromCollisionFaceIndex(faceIndex, sectionIndex); and I get a material interface which I recast into a UMaterialInstance.
My problem now lies in how to get the roughness and other lighting constants from it. I am currently looking out into the TextureParameterValues but not sure if it’s actually there.