Advertisement
orfeasel

Sphere Raycasting

Dec 23rd, 2015
5,938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. void ASweepActor::BeginPlay()
  2. {
  3.     Super::BeginPlay();
  4.  
  5.     /*TArray is the collection that contains all the HitResults*/
  6.     TArray<FHitResult> HitResults;
  7.  
  8.     /*The Start location of the sphere*/
  9.     FVector StartLocation = GetActorLocation();
  10.  
  11.     /*The End location of the sphere is equal to the default location of the actor plus the height we will enter from the editor
  12.     To extend this functionality, you can replace the height variable with a FVector*/
  13.     FVector EndLocation = GetActorLocation();
  14.     EndLocation.Z += SphereHeight;
  15.  
  16.     /*Search for static objects only*/
  17.     ECollisionChannel ECC = ECollisionChannel::ECC_WorldStatic;
  18.  
  19.     /*Declare the Collision Shape, assign a Sphere shape and set it's radius*/
  20.     FCollisionShape CollisionShape;
  21.     CollisionShape.ShapeType = ECollisionShape::Sphere;
  22.     CollisionShape.SetSphere(SphereRadius);
  23.  
  24.     /*Perform the actual raycast. This method returns true if there is at least 1 hit.*/
  25.     bool bHitSomething = GetWorld()->SweepMultiByChannel(HitResults, StartLocation, EndLocation, FQuat::FQuat(), ECC, CollisionShape);
  26.  
  27.     /*If the raycast hit a number of objects, iterate through them and print their name in the console*/
  28.     if (bHitSomething)
  29.     {
  30.         for (auto It = HitResults.CreateIterator(); It; It++)
  31.         {
  32.             GLog->Log((*It).Actor->GetName());
  33.         }
  34.     }
  35.  
  36.     /*In order to draw the sphere of the first image, I will use the DrawDebugSphere function which resides in the DrawDebugHelpers.h
  37.     This function needs the center of the sphere which in this case is provided by the following equation*/
  38.     FVector CenterOfSphere = ((EndLocation - StartLocation) / 2) + StartLocation;
  39.  
  40.     /*Draw the sphere in the viewport*/
  41.     DrawDebugSphere(GetWorld(), CenterOfSphere, CollisionShape.GetSphereRadius(), Segments, FColor::Green, true);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement