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 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);
    }
}
Beispiel #3
0
/*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 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);
}
Beispiel #5
0
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;
	}
}
Beispiel #6
0
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();
		}*/
	}
	
}
Beispiel #7
0
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());
	}
}
Beispiel #8
0
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 UARFXEffectComponent::SpawnEffectOnHitLoc_Implementation(UParticleSystem* FXIn, FHitResult HitLocation, APawn* Causer)
{
	if (!HitLocation.GetActor() && !FXIn)
		return;

	UParticleSystemComponent* ImpactPSC = UGameplayStatics::SpawnEmitterAtLocation(HitLocation.GetActor(), FXIn, HitLocation.ImpactPoint);
}
//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 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 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();
	}
}
Beispiel #15
0
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);
	}
}
// 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;
}
Beispiel #18
0
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() );
			}
		}
	}
}
Beispiel #20
0
bool ASwoim::TraceAhead(const FVector& Start, const FVector& End, UWorld* World, FHitResult& HitOut) {
	if (!World)
	{
		return false;
	}
	bool ReturnPhysMat = false;
	FCollisionQueryParams TraceParams(FName(TEXT("VictoreCore Trace")), true, this);
	TraceParams.bTraceComplex = true;
	TraceParams.bReturnPhysicalMaterial = ReturnPhysMat;
	TraceParams.AddIgnoredActor(this);

	ECollisionChannel CollisionChannel = ECollisionChannel::ECC_WorldStatic;
	//Re-initialize hit info
	HitOut = FHitResult(ForceInit);

	//Trace!
	World->LineTraceSingleByChannel(
		HitOut,		//result
		Start,	//start
		End, //end
		CollisionChannel, //collision channel
		TraceParams
		);

	//Hit any Actor?
	return (HitOut.GetActor() != NULL);

}
Beispiel #21
0
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 ATraceWeapon::HitResult(FHitResult Impact, const FVector Origin, FVector ShootDir)
{
	FVector EndTrace = Origin + ShootDir * Range;
	FVector EndPoint = Impact.GetActor() ? Impact.ImpactPoint : EndTrace;
	DrawDebugLine(this->GetWorld(), Origin, Impact.TraceEnd, FColor::Blue, false, 0.2f, 10.f, 2.f);



	if (Impact.GetActor())
	{


		UGameplayStatics::ApplyDamage(Impact.GetActor(), DamageDealt, Instigator->GetController(), Instigator, UDamageType::StaticClass());

	}
}
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);
}
Beispiel #24
0
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;
}
Beispiel #25
0
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"));
	}
}
AActor* ASrPlayerController::GetFriendlyTargetUnderCursor(const FVector2D& ScreenPoint, FVector& WorldImpactPoint) const
{
	FHitResult Hit;
	if (GetHitResultAtScreenPosition(ScreenPoint, COLLISION_WEAPON, true, Hit))
	{
		auto HitActor = Hit.GetActor();
		if (HitActor && HitActor->Implements<USrSelectionInterface>())
		{
			if (this == ISrSelectionInterface::Execute_GetTeamController(HitActor))
			{
				WorldImpactPoint = Hit.ImpactPoint;
				return Hit.GetActor();
			}
		}
	}

	return nullptr;
}
Beispiel #27
0
void AProjectile::OnHit_Implementation(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
	IDamageInterface* damageInterface = Cast<IDamageInterface>(Hit.GetActor()); //check that the actor that has hit can receive damage

	if (damageInterface && Hit.GetActor() != this->Instigator) //Check validity of the actor's pointer
	{
		damageInterface->ReceiveDamage(this->Stats.Damage, this, Hit); //receive damage
		DeactivateProjectile();
		SpawnImpactFX(Hit);
		OnHitTarget();	//trigger blueprint event
	}
	else if (Hit.GetActor() != this->Instigator) //if the actor hit can't receive damage, deactivate the projectile (like when hitting walls)
	{
		DeactivateProjectile();
		SpawnImpactFX(Hit);
		OnHitTarget();
	}
}
Beispiel #28
0
void ALogVisualizerHUD::PostRender()
{
	static const FColor TextColor(200, 200, 128, 255);

	Super::Super::PostRender();

	if (bShowHUD)
	{
		ALogVisualizerCameraController* DebugCamController = Cast<ALogVisualizerCameraController>( PlayerOwner );
		if( DebugCamController != NULL )
		{
			FCanvasTextItem TextItem( FVector2D::ZeroVector, FText::GetEmpty(), GEngine->GetSmallFont(), TextColor);
			TextItem.FontRenderInfo = TextRenderInfo;
			float X = Canvas->SizeX * 0.025f+1;
			float Y = Canvas->SizeX * 0.025f+1;

			FVector const CamLoc = DebugCamController->PlayerCameraManager->GetCameraLocation();
			FRotator const CamRot = DebugCamController->PlayerCameraManager->GetCameraRotation();

			FCollisionQueryParams TraceParams(NAME_None, true, this);
			FHitResult Hit;
			bool bHit = GetWorld()->LineTraceSingleByChannel(Hit, CamLoc, CamRot.Vector() * 100000.f + CamLoc, ECC_Pawn, TraceParams);
			if (bHit && Hit.GetActor() != nullptr)
			{
				TextItem.Text = FText::FromString(FString::Printf(TEXT("Under cursor: '%s'"), *Hit.GetActor()->GetName()));
				Canvas->DrawItem( TextItem, X, Y );
				
				DrawDebugLine( GetWorld(), Hit.Location, Hit.Location+Hit.Normal*30.f, FColor::White );
			}
			else
			{
				TextItem.Text = LOCTEXT("NotActorUnderCursor", "Not actor under cursor" );
			}
			Canvas->DrawItem( TextItem, X, Y );
			Y += TextItem.DrawnSize.Y;

			if (DebugCamController->PickedActor != NULL)
			{
				TextItem.Text = FText::FromString(FString::Printf(TEXT("Selected: '%s'"), *DebugCamController->PickedActor->GetName()));
				Canvas->DrawItem( TextItem, X, Y );				
			}
		}
	}
}
void AShooterWeapon_Instant::DealDamage(const FHitResult& Impact, const FVector& ShootDir)
{
    FPointDamageEvent PointDmg;
    PointDmg.DamageTypeClass = InstantConfig.DamageType;
    PointDmg.HitInfo = Impact;
    PointDmg.ShotDirection = ShootDir;
    PointDmg.Damage = InstantConfig.HitDamage;

    Impact.GetActor()->TakeDamage(PointDmg.Damage, PointDmg, MyPawn->Controller, this);
}
Beispiel #30
-1
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);
		}
	}

}