Advertisement
KarnakGames

Unreal Engine FindCollisionUV

Jul 13th, 2022
4,396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. bool UGameplayStatics::FindCollisionUV(const struct FHitResult& Hit, int32 UVChannel, FVector2D& UV)
  2. {
  3.     bool bSuccess = false;
  4.  
  5.     if (!UPhysicsSettings::Get()->bSupportUVFromHitResults)
  6.     {
  7.         FMessageLog("PIE").Warning(LOCTEXT("CollisionUVNoSupport", "Calling FindCollisionUV but 'Support UV From Hit Results' is not enabled in project settings. This is required for finding UV for collision results."));
  8.     }
  9.     else
  10.     {
  11.         UPrimitiveComponent* HitPrimComp = Hit.Component.Get();
  12.         if (HitPrimComp)
  13.         {
  14.             UBodySetup* BodySetup = HitPrimComp->GetBodySetup();
  15.             if (BodySetup)
  16.             {
  17.                 const FVector LocalHitPos = HitPrimComp->GetComponentToWorld().InverseTransformPosition(Hit.Location);
  18.  
  19.                 bSuccess = BodySetup->CalcUVAtLocation(LocalHitPos, Hit.FaceIndex, UVChannel, UV);
  20.             }
  21.         }
  22.     }
  23.  
  24.     return bSuccess;
  25. }
  26.  
  27. bool UBodySetup::CalcUVAtLocation(const FVector& BodySpaceLocation, int32 FaceIndex, int32 UVChannel, FVector2D& UV) const
  28. {
  29.     bool bSuccess = false;
  30.  
  31.     if (UVInfo.VertUVs.IsValidIndex(UVChannel) && UVInfo.IndexBuffer.IsValidIndex(FaceIndex * 3 + 2))
  32.     {
  33.         int32 Index0 = UVInfo.IndexBuffer[FaceIndex * 3 + 0];
  34.         int32 Index1 = UVInfo.IndexBuffer[FaceIndex * 3 + 1];
  35.         int32 Index2 = UVInfo.IndexBuffer[FaceIndex * 3 + 2];
  36.  
  37.         FVector Pos0 = UVInfo.VertPositions[Index0];
  38.         FVector Pos1 = UVInfo.VertPositions[Index1];
  39.         FVector Pos2 = UVInfo.VertPositions[Index2];
  40.  
  41.         FVector2D UV0 = UVInfo.VertUVs[UVChannel][Index0];
  42.         FVector2D UV1 = UVInfo.VertUVs[UVChannel][Index1];
  43.         FVector2D UV2 = UVInfo.VertUVs[UVChannel][Index2];
  44.  
  45.         // Transform hit location from world to local space.
  46.         // Find barycentric coords
  47.         FVector BaryCoords = FMath::ComputeBaryCentric2D(BodySpaceLocation, Pos0, Pos1, Pos2);
  48.         // Use to blend UVs
  49.         UV = (BaryCoords.X * UV0) + (BaryCoords.Y * UV1) + (BaryCoords.Z * UV2);
  50.  
  51.         bSuccess = true;
  52.     }
  53.  
  54.     return bSuccess;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement