void AShooterWeapon_Instant::ProcessInstantHit(const FHitResult& Impact, const FVector& Origin, const FVector& ShootDir, int32 RandomSeed, float ReticleSpread) { if (MyPawn && MyPawn->IsLocallyControlled() && GetNetMode() == NM_Client) { // if we're a client and we've hit something that is being controlled by the server if (Impact.GetActor() && Impact.GetActor()->GetRemoteRole() == ROLE_Authority) { // notify the server of the hit ServerNotifyHit(Impact, ShootDir, RandomSeed, ReticleSpread); } else if (Impact.GetActor() == NULL) { if (Impact.bBlockingHit) { // notify the server of the hit ServerNotifyHit(Impact, ShootDir, RandomSeed, ReticleSpread); } else { // notify server of the miss ServerNotifyMiss(ShootDir, RandomSeed, ReticleSpread); } } } // process a confirmed hit ProcessInstantHit_Confirmed(Impact, Origin, ShootDir, RandomSeed, ReticleSpread); }
void ALMPlayerController::RMouseDownSelectTarget() { FHitResult HitRes = FHitResult(); TArray<TEnumAsByte<EObjectTypeQuery>> ObjectType; //只检测一下对象 ObjectType.Add(EOBJECTTYPEQUERY_SELECTACTOR); if (GetHitResultUnderCursorForObjects(ObjectType,false,HitRes)) { if (HitRes.GetComponent() == pCurSelectedComponent) { return; } else { if (pCurSelectedComponent != nullptr) pCurSelectedComponent->SetRenderCustomDepth(false); pCurSelectedComponent = HitRes.GetComponent(); pCurSelectedComponent->SetRenderCustomDepth(true); } } }
/*Description: Raycasts forward and detects where the player is aiming to adjust the reticles*/ bool APoseidonCharacter::TraceHitForward(APlayerController* InController, FHitResult& OutTraceResult) { // Calculate the direction we are 'looking' FVector CamLoc; FRotator CamRot; InController->GetPlayerViewPoint(CamLoc, CamRot); const FVector TraceDirection = CamRot.Vector(); // Calculate the start location for trace FVector StartTrace = FVector::ZeroVector; if (InController) { FRotator UnusedRotation; InController->GetPlayerViewPoint(StartTrace, UnusedRotation); // Adjust trace so there is nothing blocking the ray between the camera and the pawn, and calculate distance from adjusted start StartTrace = StartTrace + TraceDirection * ((GetActorLocation() - StartTrace) | TraceDirection); } // Calculate endpoint of trace const FVector EndTrace = StartTrace + TraceDirection * mGrappleRange; // Setup the trace query static FName FireTraceIdent = FName(TEXT("GrappleTrace")); FCollisionQueryParams TraceParams(FireTraceIdent, true, this); TraceParams.bTraceAsyncScene = true; // Perform the trace GetWorld()->LineTraceSingleByChannel(OutTraceResult, StartTrace, EndTrace, COLLISION_GRAPPLE, TraceParams); if (OutTraceResult.GetActor() != NULL) { FString filterEnemy = TEXT("Character"); if (OutTraceResult.GetActor()->GetHumanReadableName().Contains(filterEnemy)) { if (mIsGrappleReady) { PlayerHUD->ChangeCrosshair(EReticleEnum::RE_HIT_AIM); } } else { if (mIsGrappleReady) { PlayerHUD->ChangeCrosshair(EReticleEnum::RE_AIM); } else { PlayerHUD->ChangeCrosshair(EReticleEnum::RE_HIP); } } return true; } PlayerHUD->ChangeCrosshair(EReticleEnum::RE_HIP); return false; }
void AMainPlayerController::ChooseTargetUnderMouseCursor() { /*if (clickedPawn != nullptr) { delete clickedPawn; clickedPawn = nullptr; }*/ // Trace to see what is under the mouse cursor FHitResult Hit; GetHitResultUnderCursor(ECC_Pawn, false, Hit); if (Hit.bBlockingHit) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Magenta, Hit.GetActor()->GetName()); IGlobalMapInterface * mapObj = Cast<IGlobalMapInterface>(Hit.GetActor()); clickedPawn = Cast<ABasicCharacter>(Hit.GetActor()); if (mapObj != nullptr) { mapObj->showObjectInformation(); } /*if (clickedPawn == nullptr) { Cast<IGlobalMapInterface>(Hit.GetActor())->showObjectInformation(); }*/ } }
void UCheatManager::DamageTarget(float DamageAmount) { APlayerController* const MyPC = GetOuterAPlayerController(); if ((MyPC == NULL) || (MyPC->PlayerCameraManager == NULL)) { return; } check(GetWorld() != NULL); FVector const CamLoc = MyPC->PlayerCameraManager->GetCameraLocation(); FRotator const CamRot = MyPC->PlayerCameraManager->GetCameraRotation(); FCollisionQueryParams TraceParams(NAME_None, true, MyPC->GetPawn()); FHitResult Hit; bool bHit = GetWorld()->LineTraceSingle(Hit, CamLoc, CamRot.Vector() * 100000.f + CamLoc, ECC_Pawn, TraceParams); if (bHit) { check(Hit.GetActor() != NULL); FVector ActorForward, ActorSide, ActorUp; FRotationMatrix(Hit.GetActor()->GetActorRotation()).GetScaledAxes(ActorForward, ActorSide, ActorUp); FPointDamageEvent DamageEvent(DamageAmount, Hit, -ActorForward, UDamageType::StaticClass()); Hit.GetActor()->TakeDamage(DamageAmount, DamageEvent, MyPC, MyPC->GetPawn()); } }
void UCheatManager::DestroyTarget() { APlayerController* const MyPC = GetOuterAPlayerController(); if ((MyPC == NULL) || (MyPC->PlayerCameraManager == NULL)) { return; } check(GetWorld() != NULL); FVector const CamLoc = MyPC->PlayerCameraManager->GetCameraLocation(); FRotator const CamRot = MyPC->PlayerCameraManager->GetCameraRotation(); FCollisionQueryParams TraceParams(NAME_None, true, MyPC->GetPawn()); FHitResult Hit; bool bHit = GetWorld()->LineTraceSingle(Hit, CamLoc, CamRot.Vector() * 100000.f + CamLoc, ECC_Pawn, TraceParams); if (bHit) { check(Hit.GetActor() != NULL); APawn* Pawn = Cast<APawn>(Hit.GetActor()); if (Pawn != NULL) { if ((Pawn->Controller != NULL) && (Cast<APlayerController>(Pawn->Controller) == NULL)) { // Destroy any associated controller as long as it's not a player controller. Pawn->Controller->Destroy(); } } Hit.GetActor()->Destroy(); } }
void ASWeaponInstant::ProcessInstantHit(const FHitResult& Impact, const FVector& Origin, const FVector& ShootDir) { if (MyPawn && MyPawn->IsLocallyControlled() && GetNetMode() == NM_Client) { // If we are a client and hit something that is controlled by server if (Impact.GetActor() && Impact.GetActor()->GetRemoteRole() == ROLE_Authority) { // Notify the server of our local hit to validate and apply actual hit damage. ServerNotifyHit(Impact, ShootDir); } else if (Impact.GetActor() == nullptr) { if (Impact.bBlockingHit) { ServerNotifyHit(Impact, ShootDir); } else { ServerNotifyMiss(ShootDir); } } } // Process a confirmed hit. ProcessInstantHitConfirmed(Impact, Origin, ShootDir); }
void ABaseWeapon::Instant_Fire() { const int32 RandomSeed = FMath::Rand(); FRandomStream WeaponRandomStream(RandomSeed); const float CurrentSpread = WeaponConfig.WeaponSpread; const float SpreadCone = FMath::DegreesToRadians(WeaponConfig.WeaponSpread * 0.5); const FVector AimDir = MyPawn->GetActorForwardVector(); const FVector StartTrace = MyPawn->GetActorLocation(); const FVector ShootDir = WeaponRandomStream.VRandCone(AimDir, SpreadCone, SpreadCone); FVector EndTrace; if (Target) { FVector TargetDir = (MyPawn->GetActorLocation() - Target->GetActorLocation()); TargetDir.Normalize(); FVector ShootDir2 = WeaponRandomStream.VRandCone(-TargetDir, SpreadCone, SpreadCone); EndTrace = StartTrace + ShootDir2 * WeaponConfig.WeaponRange; } else { EndTrace = StartTrace + ShootDir * WeaponConfig.WeaponRange; } const FHitResult Impact = WeaponTrace(StartTrace, EndTrace); SpawnParticle(EndTrace); HitActor = Cast<AActor>(Impact.GetActor()); //DrawDebugLine(GetWorld(), StartTrace, EndTrace, FColor::Red, false, 1.0f); if (HitActor) { Server_DealDamage(Impact, ShootDir, WeaponConfig); } }
void UCarditWeapon::Fire() { auto Camera = Cast<ACarditCharacter>(GetOwner())->GetCamera(); auto CameraLocation = Camera->GetComponentLocation(); auto EndLocation = Camera->GetComponentLocation() + (Camera->GetComponentRotation().Vector() * MaxRangeInCm); DrawDebugLine(GetWorld(), CameraLocation, EndLocation, FColor(255, 0, 0), false, 5.f, 0, 2.5f); FHitResult OutHit; if (GetWorld()->LineTraceSingleByChannel( OutHit, CameraLocation, EndLocation, ECC_Visibility ) ) { if (Cast<ACarditCharacter>(OutHit.GetActor())) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, "Character hit"); Cast<ACarditGameMode>(UGameplayStatics::GetGameMode(GetWorld()))->DealDamageOntoCharacter(Cast<ACarditCharacter>(OutHit.GetActor()), DamagePerShot); } else { UE_LOG(LogTemp, Warning, TEXT("Non-character hit")); } } else { UE_LOG(LogTemp, Warning, TEXT("Nothing hit")); } }
const FHitResult UGrabber::GetFirstPhysicsBodyInReach() { /// Get Player position and view data FVector PlayerViewPointLocation; FRotator PlayerViewPointRotation; GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(OUT PlayerViewPointLocation, OUT PlayerViewPointRotation); /*UE_LOG(LogTemp, Warning, TEXT("Location: %s, Rotation: %s"), *PlayerViewPointLocation.ToString(), *PlayerViewPointRotation.ToString());*/ /// Draw Debug Line based on how far can reach FVector LineTraceEnd = PlayerViewPointLocation + (PlayerViewPointRotation.Vector() * Reach); //DrawDebugLine(GetWorld(), PlayerViewPointLocation, LineTraceEnd, FColor(255, 0, 0), false, 0.f, 0.f, 10.f); /// Decide what can detect as collision FCollisionQueryParams TraceParameters(FName(TEXT("")), false, GetOwner()); FHitResult LineTraceHit; GetWorld()->LineTraceSingleByObjectType(OUT LineTraceHit, PlayerViewPointLocation, LineTraceEnd, FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody), TraceParameters); AActor* ActorHit = LineTraceHit.GetActor(); if (ActorHit) { UE_LOG(LogTemp, Warning, TEXT("Line Trace Hit: %s"), *(ActorHit->GetName())); } return LineTraceHit; }
void UARFXEffectComponent::SpawnEffectOnHitLoc_Implementation(UParticleSystem* FXIn, FHitResult HitLocation, APawn* Causer) { if (!HitLocation.GetActor() && !FXIn) return; UParticleSystemComponent* ImpactPSC = UGameplayStatics::SpawnEmitterAtLocation(HitLocation.GetActor(), FXIn, HitLocation.ImpactPoint); }
void AShooterWeapon_Instant::ProcessInstantHit_Confirmed(const FHitResult& Impact, const FVector& Origin, const FVector& ShootDir, int32 RandomSeed, float ReticleSpread) { // handle damage if (ShouldDealDamage(Impact.GetActor())) { DealDamage(Impact, ShootDir); } // play FX on remote clients if (Role == ROLE_Authority) { HitNotify.Origin = Origin; HitNotify.RandomSeed = RandomSeed; HitNotify.ReticleSpread = ReticleSpread; } // play FX locally if (GetNetMode() != NM_DedicatedServer) { const FVector EndTrace = Origin + ShootDir * InstantConfig.WeaponRange; const FVector EndPoint = Impact.GetActor() ? Impact.ImpactPoint : EndTrace; SpawnTrailEffect(EndPoint); SpawnImpactEffects(Impact); } }
// Called every frame void AMovingPlatform::Tick(float DeltaTime) { Super::Tick(DeltaTime); FVector currentPos = movingObject->GetComponentLocation(); if (pauseTimer > 0.0f) { pauseTimer -= DeltaTime; } else { t = smoothInterpolate->UpdatePosition(currentPos, DeltaTime); } // update lerp t if (t > 1.0f) { pauseTimer = pauseTime; t = 0.0f; delete smoothInterpolate; if (direction) { direction = false; smoothInterpolate = new SmoothInterpolate(startPos, sloopDist, distToTarget, moveSpeed, sloopPower, sloopMult, 0.0f); } else { direction = true; smoothInterpolate = new SmoothInterpolate(targetPos->GetComponentLocation(), sloopDist, distToTarget, moveSpeed, sloopPower, sloopMult, 0.0f); } } // calculate movment if (direction) { newPos = MathUtil::Lerp(targetPos->GetComponentLocation(), startPos, t); } else { newPos = MathUtil::Lerp(startPos, targetPos->GetComponentLocation(), t); } time += DeltaTime; // move FHitResult* moveHitResult = new FHitResult(); ETeleportType teleType = teleportType ? ETeleportType::TeleportPhysics : ETeleportType::None; movingObject->AddWorldOffset(newPos - movingObject->GetComponentLocation(), bSweep, moveHitResult, teleType); if (bSweep && !moveHitResult->IsValidBlockingHit()) { movingObject->AddWorldOffset(newPos - movingObject->GetComponentLocation(), false, moveHitResult, teleType); } else { smoothInterpolate->SetOldInterpolation(); } //UE_LOG(LogTemp, Warning, TEXT("ReceiveHit - IsValidBlockingHit: %d - time: %d"), moveHitResult->IsValidBlockingHit() , time); delete moveHitResult; }
//USE BUTTON CODE// void APlayerCharacter::ActivateButton() { UPeterAnimInstance* PeterAnimInstance = Cast<UPeterAnimInstance>(GetMesh()->GetAnimInstance()); if (PeterAnimInstance) { PeterAnimInstance->bIsInteracting = true; } if (PhysicsHandleActive) { PhysicsHandleActive = false; } else if (!PhysicsHandleActive) { PhysicsHandleActive = true; } bool TraceSuccess; FHitResult OutHit; //Uses Trace Channel: PlayerTrace TraceSuccess = this->TraceFromSelf(OutHit, 300.f, ECollisionChannel::ECC_GameTraceChannel6); if (TraceSuccess) { AInteractable* InteractableObject = NULL; InteractableObject = Cast<AInteractable>(OutHit.GetActor()); if (Cast<ALiftableBox>(OutHit.GetActor())) { if (PhysicsHandleActive) { PickedUpBox = Cast<ALiftableBox>(OutHit.GetActor()); if (PickedUpBox->bIsAbove(this) && PickedUpBox->CanBeLifted == true) { PhysicsHandler->GrabComponent(OutHit.GetComponent(), OutHit.BoneName, OutHit.Location, true); } } return; } else if (InteractableObject && InteractableObject->GetClass()->IsChildOf(ALightSwitch::StaticClass()) == false) { if (FVector::Dist(GetActorLocation(), InteractableObject->GetActorLocation()) < 250) { InteractableObject->Interact(this); } } } }
void AStealthArea::CalculateVisibility(AGameCharacter* calculatingUnit, TArray<AGameCharacter*>& sightList, TArray<AGameCharacter*>& availableUnits) { if (!IsValid(calculatingUnit)) return; //first get visible units on the outside based on increased radial area TArray<AActor*> ignoreList; for (AGameCharacter* gc : availableUnits) ignoreList.AddUnique(gc); for (AGameCharacter* gc : availableUnits) { if (occupyingUnits.Contains(gc)) //don't account for units in this area yet continue; if (gc->GetTeamIndex() == calculatingUnit->GetTeamIndex()) { sightList.AddUnique(gc); continue; } FVector start = GetActorLocation(); FVector end = gc->GetActorLocation(); if ((start - end).SizeSquared2D() <= FMath::Square(calculatingUnit->sightRadius * 1.15f)) { FHitResult hit; FCollisionQueryParams collisionParams; TArray<AActor*> ignoredActors = ignoreList; ignoredActors.Remove(gc); collisionParams.AddIgnoredActors(ignoredActors); collisionParams.AddIgnoredActor(this); GetWorld()->LineTraceSingleByChannel(hit, start, end, ECC_Visibility, collisionParams); if (hit.GetActor() == gc) { if (!IsValid(gc->currentStealthArea)) sightList.AddUnique(gc); } } } //finally add all of the units that are currently in the area for (AGameCharacter* gc : occupyingUnits) { if (IsValid(gc)) sightList.AddUnique(gc); else sightList.Remove(gc); } }
void ASWeaponInstant::SimulateInstantHit(const FVector& Origin) { const FVector StartTrace = Origin; const FVector AimDir = GetAdjustedAim(); const FVector EndTrace = StartTrace + (AimDir * WeaponRange); const FHitResult Impact = WeaponTrace(StartTrace, EndTrace); if (Impact.bBlockingHit) { SpawnImpactEffects(Impact); SpawnTrailEffects(Impact.ImpactPoint); } else { SpawnTrailEffects(EndTrace); } // Do not spawn near-hit if we actually hit a pawn if (Impact.GetActor() && Impact.GetActor()->IsA(ASCharacter::StaticClass())) { return; } for (FConstPawnIterator It = GetWorld()->GetPawnIterator(); It; It++) { // Find a locally controlled pawn that is not the instigator of the hit. ASCharacter* OtherPawn = Cast<ASCharacter>(*It); if (OtherPawn && OtherPawn != GetPawnOwner() && OtherPawn->IsLocallyControlled()) { // Calculate shortest distance to point. (using the estimated eye height) const float DistanceToPawn = FVector::CrossProduct(AimDir, OtherPawn->GetActorLocation() - Origin).Size(); /* Owner can be lost before client gets to simulate the hit. */ ASCharacter* P = GetPawnOwner(); if (P) { FVector LookAt = (OtherPawn->GetActorLocation() - GetPawnOwner()->GetActorLocation()); LookAt.Normalize(); float LookDot = FVector::DotProduct(AimDir, LookAt); if (DistanceToPawn < NearHitMaxDistance && LookDot > 0) { // TODO: Play at nearest "almost" hit location. const FVector SoundLocation = Origin + (AimDir * DistanceToPawn); // Volume is based on distance to missed shot float Volume = FMath::Clamp(1 - (DistanceToPawn / NearHitMaxDistance), 0.1f, 1.0f); UGameplayStatics::PlaySoundAtLocation(this, NearHitSound, /*SoundLocation*/ OtherPawn->GetActorLocation(), Volume); } } } } }
void APuzzlePresetPlayerController::OnTakeStonePressed() { // Trace to see what is under the mouse cursor FHitResult Hit; GetHitResultUnderCursor(ECC_Visibility, false, Hit); movedStone = Cast<APuzzlePresetBlock>(Hit.GetActor()); if (Hit.bBlockingHit && movedStone != nullptr) { movedStone->SetIsDragged(true); } }
void AFP_FirstPersonCharacter::OnFire() { // Play a sound if there is one if (FireSound != NULL) { UGameplayStatics::PlaySoundAtLocation(this, FireSound, GetActorLocation()); } // try and play a firing animation if specified if(FireAnimation != NULL) { // Get the animation object for the arms mesh UAnimInstance* AnimInstance = Mesh1P->GetAnimInstance(); if(AnimInstance != NULL) { AnimInstance->Montage_Play(FireAnimation, 1.f); } } // Now send a trace from the end of our gun to see if we should hit anything APlayerController* PlayerController = Cast<APlayerController>(GetController()); // Calculate the direction of fire and the start location for trace FVector CamLoc; FRotator CamRot; PlayerController->GetPlayerViewPoint(CamLoc, CamRot); const FVector ShootDir = CamRot.Vector(); FVector StartTrace = FVector::ZeroVector; if (PlayerController) { FRotator UnusedRot; PlayerController->GetPlayerViewPoint(StartTrace, UnusedRot); // Adjust trace so there is nothing blocking the ray between the camera and the pawn, and calculate distance from adjusted start StartTrace = StartTrace + ShootDir * ((GetActorLocation() - StartTrace) | ShootDir); } // Calculate endpoint of trace const FVector EndTrace = StartTrace + ShootDir * WeaponRange; // Check for impact const FHitResult Impact = WeaponTrace(StartTrace, EndTrace); // Deal with impact AActor* DamagedActor = Impact.GetActor(); UPrimitiveComponent* DamagedComponent = Impact.GetComponent(); // If we hit an actor, with a component that is simulating physics, apply an impulse if ((DamagedActor != NULL) && (DamagedActor != this) && (DamagedComponent != NULL) && DamagedComponent->IsSimulatingPhysics()) { DamagedComponent->AddImpulseAtLocation(ShootDir*WeaponDamage, Impact.Location); } }
void UARFXEffectComponent::AttachEffectToTarget_Implementation(UParticleSystem* FXIn, FHitResult Target, FName AttachSocket, APawn* Causer) { if (!Target.GetActor() && !PresitentFX) return; AARCharacter* hitTarget = Cast<AARCharacter>(Target.GetActor()); if (!hitTarget) return; UParticleSystemComponent* AttachedPSC = UGameplayStatics::SpawnEmitterAttached(PresitentFX, hitTarget->Mesh, AttachSocket); }
void ASWeaponInstant::ServerNotifyHit_Implementation(const FHitResult Impact, FVector_NetQuantizeNormal ShootDir) { // If we have an instigator, calculate the dot between the view and the shot if (Instigator && (Impact.GetActor() || Impact.bBlockingHit)) { const FVector Origin = GetMuzzleLocation(); const FVector ViewDir = (Impact.Location - Origin).GetSafeNormal(); const float ViewDotHitDir = FVector::DotProduct(Instigator->GetViewRotation().Vector(), ViewDir); if (ViewDotHitDir > AllowedViewDotHitDir) { // TODO: Check for weapon state if (Impact.GetActor() == nullptr) { if (Impact.bBlockingHit) { ProcessInstantHitConfirmed(Impact, Origin, ShootDir); } } // Assume it told the truth about static things because we don't move and the hit // usually doesn't have significant gameplay implications else if (Impact.GetActor()->IsRootComponentStatic() || Impact.GetActor()->IsRootComponentStationary()) { ProcessInstantHitConfirmed(Impact, Origin, ShootDir); } else { const FBox HitBox = Impact.GetActor()->GetComponentsBoundingBox(); FVector BoxExtent = 0.5 * (HitBox.Max - HitBox.Min); BoxExtent *= ClientSideHitLeeway; BoxExtent.X = FMath::Max(20.0f, BoxExtent.X); BoxExtent.Y = FMath::Max(20.0f, BoxExtent.Y); BoxExtent.Z = FMath::Max(20.0f, BoxExtent.Z); const FVector BoxCenter = (HitBox.Min + HitBox.Max) * 0.5; // If we are within client tolerance if (FMath::Abs(Impact.Location.Z - BoxCenter.Z) < BoxExtent.Z && FMath::Abs(Impact.Location.X - BoxCenter.X) < BoxExtent.X && FMath::Abs(Impact.Location.Y - BoxCenter.Y) < BoxExtent.Y) { ProcessInstantHitConfirmed(Impact, Origin, ShootDir); } } } } // TODO: UE_LOG on failures & rejection }
void AWeapon::ProcessInstantHit(const FHitResult &Impact, const FVector &Origin, const FVector &ShootDir, int32 RandomSeed, float ReticleSpread) { const FVector EndTrace = Origin + ShootDir * WeaponConfig.WeaponRange; const FVector EndPoint = Impact.GetActor() ? Impact.ImpactPoint : EndTrace; DrawDebugLine(this->GetWorld(), Origin, Impact.TraceEnd, FColor::Black, true, 10000, 10.f); AEnemy *Enemy = Cast<AEnemy>(Impact.GetActor()); if (Enemy) { GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Red, "YOU HIT AN ENEMY!!"); Enemy->Destroy(); } }
void UGrabber::Grab() { UE_LOG(LogTemp, Warning, TEXT("Grab!!")); FHitResult hitResult = GetFirstPhysicsBodyInReach(); auto ActorHit = hitResult.GetActor(); if (ActorHit != nullptr) { auto ComponentToGrab = hitResult.GetComponent(); //Try and reach any actors with physics body and then attach them physicsHandle->GrabComponent(ComponentToGrab, NAME_None, ComponentToGrab->GetOwner()->GetActorLocation(), true); } }
void AWeaponBase::DealDamage(const FHitResult& Hit){ if(Hit.GetActor()){ float DealtDamage = BaseDamage; FVector ShotDir = GetActorLocation() - Hit.ImpactPoint; FPointDamageEvent DamageEvent; DamageEvent.Damage = DealtDamage; DamageEvent.HitInfo = Hit; DamageEvent.ShotDirection = ShotDir; DamageEvent.ShotDirection.Normalize(); Hit.GetActor()->TakeDamage(DealtDamage, DamageEvent, OwningPlayer->GetController(), this); } }
void AKIMCharacter::Interact() { if (IsInRoationState && PickedUpItem) { ((AKIMInteractionActor*)PickedUpItem)->LayBack(this); return; } FHitResult outHit; FCollisionQueryParams params; params.AddIgnoredActor(this); params.AddIgnoredActor(PickedUpItem); FVector TraceStart = CameraComponent->GetComponentLocation(); FVector TraceEnd = TraceStart + (CameraComponent->GetForwardVector() * InteractionDistance); GetWorld()->LineTraceSingleByChannel(outHit, TraceStart, TraceEnd, ECollisionChannel::ECC_PhysicsBody, params); if (outHit.GetActor() != NULL && outHit.GetActor()->GetClass()->IsChildOf(AKIMInteractionActor::StaticClass())) { AKIMInteractionActor* InteractionActor = ((AKIMInteractionActor*)outHit.GetActor()); InteractionActor->Interacted(this, outHit.GetComponent()); UE_LOG(LogClass, Warning, TEXT("Interacted with %s"), *outHit.GetActor()->GetName()); UE_LOG(LogClass, Warning, TEXT("(%s)"), *outHit.GetComponent()->GetName()); } else if (outHit.GetActor() == NULL && PickedUpItem) { PickedUpItem->DetachRootComponentFromParent(true); ((AKIMInteractionActor*)PickedUpItem)->Droped(); ((AKIMInteractionActor*)PickedUpItem)->InteractionType = EKIMInteractionTypes::OnPickUp; UE_LOG(LogClass, Warning, TEXT("Droped %s"), *PickedUpItem->GetName()); PickedUpItem = NULL; } }
// executes the task when called EBTNodeResult::Type UAIE_UseItem_BTTaskNode::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { /* call super * should aquire refrences for our BehaviorTreeComp, BlackboardComp, AIController, and BotCharacter * will return EBTNodeResult::Succeeded if we have all of them * will return EBTNodeResult::Failed if it failed to grab any of them */ EBTNodeResult::Type resultFromSuperExecution = Super::ExecuteTask(OwnerComp, NodeMemory); // check that we successfully grabbed the BehaviorTreeComp, BlackboardComp, AIController, and BotCharacter // check that our bot implements the is Usable interface if (resultFromSuperExecution == EBTNodeResult::Succeeded && BotCharacter->GetClass()->ImplementsInterface(UAIE_IsUsable::StaticClass())) { // get our object from blackboard key FBlackboard::FKey DesiredObjectKey = Blackboard->GetKeyID("DesiredObject"); // check that our key is valid if (Blackboard->IsValidKey(DesiredObjectKey)) { // store our object as an actor AActor* desiredObjectActor = Cast<AActor>(Blackboard->GetValue<UBlackboardKeyType_Object>(DesiredObjectKey)); // get the distance from our object float distance = FVector::Dist(desiredObjectActor->GetActorLocation(), BotCharacter->GetActorLocation()); // compare distance to max reach if (distance <= MaxReach) { // array of actors to ignore TArray<AActor*> actorsToIgnore; // the bot can't get in the way of itself actorsToIgnore.Add(BotCharacter); // will hold our hit result FHitResult hit; // fire the trace and check if we hit something if (UAIE_StaticLibrary::Trace(GetWorld(), actorsToIgnore, BotCharacter->GetActorLocation(), desiredObjectActor->GetActorLocation(), hit, ECollisionChannel::ECC_WorldDynamic, false, true)) { #if !UE_BUILD_SHIPPING GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, hit.GetActor()->GetName() + " grab object"); #endif if (hit.GetActor() == desiredObjectActor) { #if !UE_BUILD_SHIPPING GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, BotCharacter->BotName.ToString() + " trying to grab object"); #endif // exacute AI_UseItem on our bot with the Desired object IAIE_IsUsable::Execute_AI_ActivateUseItem(BotCharacter, desiredObjectActor); // return success return EBTNodeResult::Succeeded; } } } } } // return failed return EBTNodeResult::Failed; }
float UAISense_Aquaphobia::Update() { AIPerception::FListenerMap& ListenersMap = *GetListeners(); //For each listener who has this sense we're going to perform a sweep to determine nearby aqua actors for (auto& Elem : ListenersMap) { //Get the listener FPerceptionListener Listener = Elem.Value; const AActor* ListenerBodyActor = Listener.GetBodyActor(); for (int32 DigestedPropertyIndex = 0; DigestedPropertyIndex < DigestedProperties.Num(); DigestedPropertyIndex++) { //Create the sphere for this sense and perform the sweep to determine nearby actors FCollisionShape CollisionSphere = FCollisionShape::MakeSphere(DigestedProperties[DigestedPropertyIndex].PhobiaRadius); TArray<FHitResult> HitResults; GetWorld()->SweepMultiByChannel(HitResults, ListenerBodyActor->GetActorLocation(), ListenerBodyActor->GetActorLocation() + FVector::UpVector*CollisionSphere.GetSphereRadius(), FQuat(), ECollisionChannel::ECC_WorldDynamic, CollisionSphere); //Draw debug sphere if we have activated it via the config if (DigestedProperties[DigestedPropertyIndex].bDisplayDebugSphere) { DrawDebugSphere(GetWorld(), ListenerBodyActor->GetActorLocation(), DigestedProperties[DigestedPropertyIndex].PhobiaRadius, 8, FColor::Blue, false, 30.f, 1, 2.f); } //Check hit results for aqua actors for (int32 i = 0; i < HitResults.Num(); i++) { FHitResult hit = HitResults[i]; //To simplify things, we're going to assume that "water resources" for this post are actors that have the following game tag if (hit.GetActor()->ActorHasTag(FName("AquaActor"))) { if ((hit.GetActor()->GetActorLocation() - ListenerBodyActor->GetActorLocation()).Size() <= DigestedProperties[DigestedPropertyIndex].PhobiaRadius) { Elem.Value.RegisterStimulus(hit.GetActor(), FAIStimulus(*this, 5.f, hit.GetActor()->GetActorLocation(), ListenerBodyActor->GetActorLocation())); GLog->Log("registered stimulus!"); } } } } } //Time until next update; in this case we're forcing the update to happen in each frame return 0.f; }
void AWeapon::DoDamage(FHitResult& ObjectHit) { FVector ImpactPoint; FVector ImpactNormal; ImpactPoint.X = ObjectHit.ImpactPoint.X; ImpactPoint.Y = ObjectHit.ImpactPoint.Y; ImpactPoint.Z = ObjectHit.ImpactPoint.Z; ImpactNormal.X = ObjectHit.ImpactNormal.X; //Use this data for placing decals if bullets hit walls etc. ImpactNormal.Y = ObjectHit.ImpactNormal.Y; ImpactNormal.Z = ObjectHit.ImpactNormal.Z; const UWorld* World = GetWorld(); if (World) { DrawDebugSphere(World, ImpactPoint, 10.0f, 8, FColor(255, 0, 0), false, 3, 0); APlayerController* PlayerController = Cast<APlayerController>(WeaponOwner->GetController()); if (PlayerController != nullptr) { const AActor* HitActor = ObjectHit.GetActor(); if (HitActor != nullptr) { if (HitActor->IsA(AEnemy::StaticClass())) { AEnemy* Enemy = (AEnemy*)HitActor; TSubclassOf<UDamageType> const ValidDamageTypeClass = TSubclassOf<UDamageType>(UDamageType::StaticClass()); FDamageEvent DamageEvent(ValidDamageTypeClass); Enemy->TakeDamage(Config.Damage, DamageEvent, PlayerController, this); } } } } }
void ADebugCameraController::Select( FHitResult const& Hit ) { // First untrack the currently tracked lightmap. UTexture2D* Texture2D = GDebugSelectedLightmap ? GDebugSelectedLightmap->GetTexture(0) : NULL; if ( Texture2D ) { UntrackTexture( Texture2D->GetName() ); } // store selection SelectedActor = Hit.GetActor(); SelectedComponent = Hit.Component.Get(); GDebugSelectedActor = SelectedActor; GDebugSelectedComponent = SelectedComponent; // figure out lightmap GDebugSelectedLightmap = NULL; UStaticMeshComponent* StaticMeshComponent = Cast<UStaticMeshComponent>( SelectedComponent ); if ( StaticMeshComponent && StaticMeshComponent->LODData.Num() > 0 ) { const FStaticMeshComponentLODInfo& LODInfo = StaticMeshComponent->LODData[0]; if ( LODInfo.LightMap ) { GDebugSelectedLightmap = LODInfo.LightMap->GetLightMap2D(); Texture2D = GDebugSelectedLightmap ? GDebugSelectedLightmap->GetTexture(0) : NULL; if ( Texture2D ) { extern bool TrackTexture( const FString& TextureName ); TrackTexture( Texture2D->GetName() ); } } } }
void ASWeaponInstant::DealDamage(const FHitResult& Impact, const FVector& ShootDir) { float ActualHitDamage = HitDamage; /* Handle special damage location on the zombie body (types are setup in the Physics Asset of the zombie */ USDamageType* DmgType = Cast<USDamageType>(DamageType->GetDefaultObject()); UPhysicalMaterial * PhysMat = Impact.PhysMaterial.Get(); if (PhysMat && DmgType) { if (PhysMat->SurfaceType == SURFACE_ZOMBIEHEAD) { ActualHitDamage *= DmgType->GetHeadDamageModifier(); } else if (PhysMat->SurfaceType == SURFACE_ZOMBIELIMB) { ActualHitDamage *= DmgType->GetLimbDamageModifier(); } } FPointDamageEvent PointDmg; PointDmg.DamageTypeClass = DamageType; PointDmg.HitInfo = Impact; PointDmg.ShotDirection = ShootDir; PointDmg.Damage = ActualHitDamage; Impact.GetActor()->TakeDamage(PointDmg.Damage, PointDmg, MyPawn->Controller, this); }
void AKIMCharacter::CheckTraceDistance() { if (IsInRoationState) { return; } FHitResult outHit; FCollisionQueryParams params; params.AddIgnoredActor(this); params.AddIgnoredActor(PickedUpItem); FVector TraceStart = CameraComponent->GetComponentLocation(); FVector TraceEnd = TraceStart + (CameraComponent->GetForwardVector() * InteractionDistance); GetWorld()->LineTraceSingleByChannel(outHit, TraceStart, TraceEnd, ECollisionChannel::ECC_PhysicsBody, params); if (outHit.GetActor() != NULL && outHit.GetActor()->GetClass()->IsChildOf(AKIMInteractionActor::StaticClass())) { if (((AKIMInteractionActor*)outHit.GetActor())->InteractionType != StoredType){ StoredType = ((AKIMInteractionActor*)outHit.GetActor())->InteractionType; SwitchIconState(StoredType); } } else { if (StoredType != EKIMInteractionTypes::NONE) { StoredType = EKIMInteractionTypes::NONE; SwitchIconState(StoredType); } } }