Last active
July 15, 2022 09:34
-
-
Save theshaneobrien/8738668bb9803fd88707dcf1fdb24750 to your computer and use it in GitHub Desktop.
Unreal Engine Mouse Position in Screen Space to World Location then Sweep / LineCast / RayCast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void USelectionController::TryGetUnitAtMousePos() | |
{ | |
// This is the variable that will be populated by whatever we hit with our sweep | |
FHitResult HitResult; | |
if(SweepToMousePos(HitResult)) | |
{ | |
HitResult.GetActor()->Tags.Add("Selected"); | |
//Draw a sphere where we hit | |
DrawDebugSphere(GetWorld(), HitResult.ImpactPoint, 100, 10,FColor::Green, false, 5); | |
//If our hit result = the type of actor we want to hit | |
if(Cast<ABaseUnit>(HitResult.GetActor())) | |
{ | |
// Do something with it | |
UnitSelectionManager->SelectSingleUnit(Cast<ABaseUnit>(HitResult.GetActor())); | |
} | |
} | |
} | |
bool USelectionController::SweepToMousePos(FHitResult& HitResult) const | |
{ | |
APlayerController* PlayerController = GetWorld()->GetFirstPlayerController(); | |
FVector WorldLocation; | |
FVector WorldDirection; | |
//This is where the mouse screen pos gets converted to world pos | |
if(PlayerController->DeprojectMousePositionToWorld(WorldLocation, WorldDirection)) | |
{ | |
//Start and end points of our sweep/trace | |
FVector Start = WorldLocation; | |
FVector End = Start + WorldDirection * 1000000; | |
DrawDebugLine(GetWorld(),Start, End, FColor::Red); | |
DrawDebugSphere(GetWorld(), End, 10, 10,FColor::Blue, false, 5); | |
//Linecast / Raycast | |
return GetWorld()->LineTraceSingleByChannel(HitResult,Start, | |
End,ECC_GameTraceChannel1); | |
//The shape we will use for our sweep | |
FCollisionShape Sphere = FCollisionShape::MakeSphere(10.f); | |
//Since we are using a sphere, we are effectively doing a "SausageCast" | |
return GetWorld()->SweepSingleByChannel(HitResult,Start, | |
End,FQuat::Identity, ECC_GameTraceChannel1, Sphere); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment