Search code examples
collision-detectioncollisionunreal-engine4mesh-collider

UE4 Mesh several collision points detecting


I need to find all hit points (vertices) when my meshes collide since with OnHit there is only one Impact point in the structure and there is only one (red debug sphere). Is there any way to do this? (for example in Unity collision struct has an array of these points: collision.contacts)

This is an example when 2 cubes are in contact with the faces and there are many contact points (not 1)

введите сюда описание изображения


Solution

  • A collision generates overlap events so you can use OnComponentBeginOverlap and get SweepResult for the overlap event in theory. But SweepResult is not too reliable so I would suggest doing a Spherical Sweep inside the overlap event.

    void Pawn::OnComponentBeginOverlap(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, 
    int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
     {
         if (OtherActor && (OtherActor != this))
         {
             TArray<FHitResult> Results;
             auto ActorLoc = GetActorLocation();
             auto OtherLoc = OtherComp->GetComponentLocation();
             auto CollisionRadius = FVector::Dist(Start, End) * 1.2f;
     
             // spherical sweep 
             GetWorld()->SweepMultiByObjectType(Results, ActorLoc, OtherLoc,
                 FQuat::Identity, 0,
                 FCollisionShape::MakeSphere(CollisionRadius),  
                 // use custom params to reduce the search space
                 FCollisionQueryParams::FCollisionQueryParams(false)
             );
     
             for (auto HitResult : Results)
             {
                 if (OtherComp->GetUniqueID() == HitResult.GetComponent()->GetUniqueID()) {
    
                 // insert your code 
    
                     break;
                 }
             }
         }
     }
    

    You could try using FCollisionQueryParams to make this process faster but spherical sweep would be drawn after a few frames of collision so maybe you could pause/stop the actor to get accurate results.