// Sets default values ASZombieCharacter::ASZombieCharacter(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { /* Note: We assign the Controller class in the Blueprint extension of this class Because the zombie AIController is a blueprint in content and it's better to avoid content references in code. */ /*AIControllerClass = ASZombieAIController::StaticClass();*/ /* Our sensing component to detect players by visibility and noise checks. */ PawnSensingComp = CreateDefaultSubobject<UPawnSensingComponent>(TEXT("PawnSensingComp")); PawnSensingComp->SetPeripheralVisionAngle(60.0f); PawnSensingComp->SightRadius = 2000; PawnSensingComp->HearingThreshold = 600; PawnSensingComp->LOSHearingThreshold = 1200; /* Ignore this channel or it will absorb the trace impacts instead of the skeletal mesh */ GetCapsuleComponent()->SetCollisionResponseToChannel(COLLISION_WEAPON, ECR_Ignore); GetCapsuleComponent()->SetCapsuleHalfHeight(96.0f, false); GetCapsuleComponent()->SetCapsuleRadius(42.0f); /* These values are matched up to the CapsuleComponent above and are used to find navigation paths */ GetMovementComponent()->NavAgentProps.AgentRadius = 42; GetMovementComponent()->NavAgentProps.AgentHeight = 192; Health = 100; PunchDamage = 10.0f; /* By default we will not let the AI patrol, we can override this value per-instance. */ BotType = EBotBehaviorType::Passive; SenseTimeOut = 2.5f; /* Note: Visual Setup is done in the AI/ZombieCharacter Blueprint file */ }
void UMyAnimInstance::NativeUpdateAnimation(float DeltaSeconds) { Super::NativeUpdateAnimation(DeltaSeconds); const auto PawnOwner = TryGetPawnOwner(); if (nullptr != PawnOwner) { //!< スピード const auto Velocity = PawnOwner->GetVelocity(); Speed = Velocity.Size(); //!< 方向 Direction = (Velocity.Rotation() - PawnOwner->GetActorRotation()).Yaw; while (Direction < -180.0f) { Direction += 360.0f; } while (Direction > 180.0f) { Direction -= 360.0f; } //!< 落下 const auto MovementComp = PawnOwner->GetMovementComponent(); if (nullptr != MovementComp) { IsFalling = MovementComp->IsFalling(); } } }
void ABaseCharacter::SetRagdollPhysics() { USkeletalMeshComponent* Mesh3P = GetMesh(); if (Mesh3P) { Mesh3P->SetCollisionProfileName(TEXT("Ragdoll")); } SetActorEnableCollision(true); if (!IsPendingKill() || Mesh3P || Mesh3P->GetPhysicsAsset()) { Mesh3P->SetAllBodiesSimulatePhysics(true); Mesh3P->SetSimulatePhysics(true); Mesh3P->WakeAllRigidBodies(); Mesh3P->bBlendPhysics = true; SetLifeSpan(TimeAfterDeathBeforeDestroy); } else { // Immediately hide the pawn TurnOff(); SetActorHiddenInGame(true); SetLifeSpan(1.0f); } UCharacterMovementComponent* CharacterComp = Cast<UCharacterMovementComponent>(GetMovementComponent()); if (CharacterComp) { CharacterComp->StopMovementImmediately(); CharacterComp->DisableMovement(); CharacterComp->SetComponentTickEnabled(false); } }
float ALD35Character::TakeDamage(float DamageAmount, FDamageEvent const & DamageEvent, AController * EventInstigator, AActor * DamageCauser) { UGameplayStatics::PlaySoundAtLocation(this, HitSound, this->GetActorLocation()); float dmg = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser); Health -= dmg; if (Health <= 0) { GetMesh()->SetSimulatePhysics(true); GetMesh()->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision); GetMovementComponent()->SetActive(false); UGameplayStatics::PlaySoundAtLocation(this, DeathSound, this->GetActorLocation()); if (EventInstigator) { if (auto a = Cast<ALD35Character>(EventInstigator->GetPawn())) { if (a->Faction == Faction) { UE_LOG(LogTemp, Display, TEXT("Teamkilling detected!")); a->Faction = FMath::Rand(); } } } } return dmg; }
void APawn::Restart() { UPawnMovementComponent* MovementComponent = GetMovementComponent(); if (MovementComponent) { MovementComponent->StopMovementImmediately(); } ConsumeMovementInputVector(); RecalculateBaseEyeHeight(); }
FVector APawn::GetVelocity() const { if(GetRootComponent() && GetRootComponent()->IsSimulatingPhysics()) { return GetRootComponent()->GetComponentVelocity(); } const UPawnMovementComponent* MovementComponent = GetMovementComponent(); return MovementComponent ? MovementComponent->Velocity : FVector::ZeroVector; }
void APawn::UpdateNavAgent() { UPawnMovementComponent* MovementComponent = GetMovementComponent(); //// Update Nav Agent props with collision component's setup if it's not set yet if (RootComponent != NULL && MovementComponent != NULL && MovementComponent->ShouldUpdateNavAgentWithOwnersCollision()) { RootComponent->UpdateBounds(); MovementComponent->UpdateNavAgent(*this); } }
void APawn::PostNetReceiveVelocity(const FVector& NewVelocity) { if (Role == ROLE_SimulatedProxy) { UMovementComponent* const MoveComponent = GetMovementComponent(); if ( MoveComponent ) { MoveComponent->Velocity = NewVelocity; } } }
void AEnemyRunCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (HasAuthority()) { IsAlive() ? RoadSplineComponent->MoveCharacterlongSplineTrack(this) : GetMovementComponent()->StopActiveMovement(); } }
FVector APawn::ConsumeMovementInputVector() { UPawnMovementComponent* MovementComponent = GetMovementComponent(); if (MovementComponent) { return MovementComponent->ConsumeInputVector(); } else { return Internal_ConsumeMovementInputVector(); } }
void APawn::AddMovementInput(FVector WorldDirection, float ScaleValue, bool bForce /*=false*/) { UPawnMovementComponent* MovementComponent = GetMovementComponent(); if (MovementComponent) { MovementComponent->AddInputVector(WorldDirection * ScaleValue, bForce); } else { Internal_AddMovementInput(WorldDirection * ScaleValue, bForce); } }
class APhysicsVolume* APawn::GetPawnPhysicsVolume() const { const UPawnMovementComponent* MovementComponent = GetMovementComponent(); if (MovementComponent) { return MovementComponent->GetPhysicsVolume(); } else if (GetRootComponent()) { return GetRootComponent()->GetPhysicsVolume(); } return GetWorld()->GetDefaultPhysicsVolume(); }
void APawn::TeleportSucceeded(bool bIsATest) { if (bIsATest == false) { UPawnMovementComponent* MovementComponent = GetMovementComponent(); if (MovementComponent) { MovementComponent->OnTeleported(); } } Super::TeleportSucceeded(bIsATest); }
ASECharacter::ASECharacter() : Super() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(5.421325f, 44.f); // Set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; auto movement = CastChecked<UCharacterMovementComponent>(GetMovementComponent()); movement->MaxWalkSpeed = 100.f; // Create a CameraComponent CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); CameraComponent->AttachToComponent(GetCapsuleComponent(), FAttachmentTransformRules::KeepWorldTransform); CameraComponent->RelativeLocation = FVector(0.f, 0.f, GetCapsuleComponent()->GetUnscaledCapsuleHalfHeight()); // Position the camera CameraComponent->bUsePawnControlRotation = true; }
void AShooterCharacter::SetRagdollPhysics() { bool bInRagdoll = false; USkeletalMeshComponent* Mesh3P = GetMesh(); if (IsPendingKill()) { bInRagdoll = false; } else if (!Mesh3P || !Mesh3P->GetPhysicsAsset()) { bInRagdoll = false; } else { Mesh3P->SetAllBodiesSimulatePhysics(true); Mesh3P->SetSimulatePhysics(true); Mesh3P->WakeAllRigidBodies(); Mesh3P->bBlendPhysics = true; bInRagdoll = true; } UCharacterMovementComponent* CharacterComp = Cast<UCharacterMovementComponent>(GetMovementComponent()); if (CharacterComp) { CharacterComp->StopMovementImmediately(); CharacterComp->DisableMovement(); CharacterComp->SetComponentTickEnabled(false); } if (!bInRagdoll) { // Immediately hide the pawn TurnOff(); SetActorHiddenInGame(true); SetLifeSpan(1.0f); } else { SetLifeSpan(10.0f); } }
void APawn::TurnOff() { if (Role == ROLE_Authority) { SetReplicates(true); } // do not block anything, just ignore SetActorEnableCollision(false); UPawnMovementComponent* MovementComponent = GetMovementComponent(); if (MovementComponent) { MovementComponent->StopMovementImmediately(); MovementComponent->SetComponentTickEnabled(false); } DisableComponentsSimulatePhysics(); }
// Called every frame void AVoyager::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); if(inBearingMode) { if( bearingModeRotationTime < 1.0f ) { bearingModeRotationTime = FMath::Clamp(bearingModeRotationTime + DeltaTime/2.0f, 0.0f, 1.0f); OurCameraSpringArm->SetWorldRotation(FMath::Lerp(initialBearingRotation, desiredBearingRotation, bearingModeRotationTime)); } float distanceFromSun = (sunReference->GetActorLocation() - GetActorLocation()).Size(); bool shouldZoomTowardsSun = distanceFromSun > desiredBearingDistanceFromSun; if(bearingModeRotationTime >= 1.0f && shouldZoomTowardsSun) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, FString::Printf(TEXT("Moving towards sun. At distance: %f"), distanceFromSun-220.0f)); OurMovementComponent->AddInputVector(OurCamera->GetForwardVector()*(DeltaTime*GetMovementComponent()->movementVelocity)); } if(bearingModeRotationTime >= 1.0f && !shouldZoomTowardsSun) { inBearingMode = false; } } }
bool APawn::IsNetRelevantFor(const AActor* RealViewer, const AActor* ViewTarget, const FVector& SrcLocation) const { CA_SUPPRESS(6011); if (bAlwaysRelevant || RealViewer == Controller || IsOwnedBy(ViewTarget) || IsOwnedBy(RealViewer) || this == ViewTarget || ViewTarget == Instigator || IsBasedOnActor(ViewTarget) || (ViewTarget && ViewTarget->IsBasedOnActor(this))) { return true; } else if( (bHidden || bOnlyRelevantToOwner) && (!GetRootComponent() || !GetRootComponent()->IsCollisionEnabled()) ) { return false; } else { UPrimitiveComponent* MovementBase = GetMovementBase(); AActor* BaseActor = MovementBase ? MovementBase->GetOwner() : NULL; if ( MovementBase && BaseActor && GetMovementComponent() && ((Cast<const USkeletalMeshComponent>(MovementBase)) || (BaseActor == GetOwner())) ) { return BaseActor->IsNetRelevantFor(RealViewer, ViewTarget, SrcLocation); } } return ((SrcLocation - GetActorLocation()).SizeSquared() < NetCullDistanceSquared); }
void ACharacter::OnRep_ReplicatedBasedMovement() { if (Role != ROLE_SimulatedProxy) { return; } // Skip base updates while playing root motion, it is handled inside of OnRep_RootMotion if (IsPlayingNetworkedRootMotionMontage()) { return; } TGuardValue<bool> bInBaseReplicationGuard(bInBaseReplication, true); const bool bBaseChanged = (BasedMovement.MovementBase != ReplicatedBasedMovement.MovementBase || BasedMovement.BoneName != ReplicatedBasedMovement.BoneName); if (bBaseChanged) { // Even though we will copy the replicated based movement info, we need to use SetBase() to set up tick dependencies and trigger notifications. SetBase(ReplicatedBasedMovement.MovementBase, ReplicatedBasedMovement.BoneName); } // Make sure to use the values of relative location/rotation etc from the server. BasedMovement = ReplicatedBasedMovement; if (ReplicatedBasedMovement.HasRelativeLocation()) { // Update transform relative to movement base const FVector OldLocation = GetActorLocation(); const FQuat OldRotation = GetActorQuat(); MovementBaseUtility::GetMovementBaseTransform(ReplicatedBasedMovement.MovementBase, ReplicatedBasedMovement.BoneName, CharacterMovement->OldBaseLocation, CharacterMovement->OldBaseQuat); const FVector NewLocation = CharacterMovement->OldBaseLocation + ReplicatedBasedMovement.Location; if (ReplicatedBasedMovement.HasRelativeRotation()) { // Relative location, relative rotation FRotator NewRotation = (FRotationMatrix(ReplicatedBasedMovement.Rotation) * FQuatRotationMatrix(CharacterMovement->OldBaseQuat)).Rotator(); // TODO: need a better way to not assume we only use Yaw. NewRotation.Pitch = 0.f; NewRotation.Roll = 0.f; SetActorLocationAndRotation(NewLocation, NewRotation); } else { // Relative location, absolute rotation SetActorLocationAndRotation(NewLocation, ReplicatedBasedMovement.Rotation); } // When position or base changes, movement mode will need to be updated. This assumes rotation changes don't affect that. CharacterMovement->bJustTeleported |= (bBaseChanged || GetActorLocation() != OldLocation); INetworkPredictionInterface* PredictionInterface = Cast<INetworkPredictionInterface>(GetMovementComponent()); if (PredictionInterface) { PredictionInterface->SmoothCorrection(OldLocation, OldRotation); } } }
void ACharacter::PostNetReceiveLocationAndRotation() { if( Role == ROLE_SimulatedProxy ) { // Don't change transform if using relative position (it should be nearly the same anyway, or base may be slightly out of sync) if (!ReplicatedBasedMovement.HasRelativeLocation()) { const FVector OldLocation = GetActorLocation(); const FQuat OldRotation = GetActorQuat(); UpdateSimulatedPosition(ReplicatedMovement.Location, ReplicatedMovement.Rotation); INetworkPredictionInterface* PredictionInterface = Cast<INetworkPredictionInterface>(GetMovementComponent()); if (PredictionInterface) { PredictionInterface->SmoothCorrection(OldLocation, OldRotation); } } } }
void ACharacter::SimulatedRootMotionPositionFixup(float DeltaSeconds) { const FAnimMontageInstance* ClientMontageInstance = GetRootMotionAnimMontageInstance(); if( ClientMontageInstance && CharacterMovement && Mesh ) { // Find most recent buffered move that we can use. const int32 MoveIndex = FindRootMotionRepMove(*ClientMontageInstance); if( MoveIndex != INDEX_NONE ) { const FVector OldLocation = GetActorLocation(); const FQuat OldRotation = GetActorQuat(); // Move Actor back to position of that buffered move. (server replicated position). const FSimulatedRootMotionReplicatedMove& RootMotionRepMove = RootMotionRepMoves[MoveIndex]; if( RestoreReplicatedMove(RootMotionRepMove) ) { const float ServerPosition = RootMotionRepMove.RootMotion.Position; const float ClientPosition = ClientMontageInstance->GetPosition(); const float DeltaPosition = (ClientPosition - ServerPosition); if( FMath::Abs(DeltaPosition) > KINDA_SMALL_NUMBER ) { // Find Root Motion delta move to get back to where we were on the client. const FTransform LocalRootMotionTransform = ClientMontageInstance->Montage->ExtractRootMotionFromTrackRange(ServerPosition, ClientPosition); // Simulate Root Motion for delta move. if( CharacterMovement ) { const float MontagePlayRate = ClientMontageInstance->GetPlayRate(); // Guess time it takes for this delta track position, so we can get falling physics accurate. if (!FMath::IsNearlyZero(MontagePlayRate)) { const float DeltaTime = DeltaPosition / MontagePlayRate; // Even with negative playrate deltatime should be positive. check(DeltaTime > 0.f); CharacterMovement->SimulateRootMotion(DeltaTime, LocalRootMotionTransform); // After movement correction, smooth out error in position if any. INetworkPredictionInterface* PredictionInterface = Cast<INetworkPredictionInterface>(GetMovementComponent()); if (PredictionInterface) { PredictionInterface->SmoothCorrection(OldLocation, OldRotation); } } } } } // Delete this move and any prior one, we don't need them anymore. UE_LOG(LogRootMotion, Log, TEXT("\tClearing old moves (%d)"), MoveIndex+1); RootMotionRepMoves.RemoveAt(0, MoveIndex+1); } } }
void AMyCharacter::MoveForward(float Scale) { GetMovementComponent()->AddInputVector(GetActorForwardVector() * Scale * 10); }
void ARadeCharacter::BeginPlay() { Super::BeginPlay(); // Get Default Third Person Mesh Relative Location and Rotation if (GetMesh()) { Mesh_InGameRelativeLoc = GetMesh()->RelativeLocation; Mesh_InGameRelativeRot = GetMesh()->RelativeRotation; } // Get Player Controller if (GetController() && Cast<ARadePC>(GetController())) { ThePC = Cast<ARadePC>(GetController()); } // Get HUD if (ThePC && ThePC->GetHUD() && Cast<ABaseHUD>(ThePC->GetHUD()))TheHUD = Cast<ABaseHUD>(ThePC->GetHUD()); // Manage Inventory if (TheInventory) { // Set player Ref in Inventory TheInventory->ThePlayer = this; // Load Inventory if (bSaveInventory && Role >= ROLE_Authority) { TheInventory->LoadInventory(); } } // Get Player Movement Component if (Cast<UCharacterMovementComponent>(GetMovementComponent())) { PlayerMovementComponent = Cast<UCharacterMovementComponent>(GetMovementComponent()); } // Get First Person Anim Instance if (Mesh1P && Mesh1P->GetAnimInstance() && Cast<URadeAnimInstance>(Mesh1P->GetAnimInstance())) ArmsAnimInstance = Cast<URadeAnimInstance>(Mesh1P->GetAnimInstance()); // Get Third Person Anim Instance if (GetMesh() && GetMesh()->GetAnimInstance() && Cast<URadeAnimInstance>(GetMesh()->GetAnimInstance())) BodyAnimInstance = Cast<URadeAnimInstance>(GetMesh()->GetAnimInstance()); // Set Player Ref in Anim Instance if (ArmsAnimInstance)ArmsAnimInstance->ThePlayer = this; if (BodyAnimInstance)BodyAnimInstance->ThePlayer = this; // Set Default Anim State ServerSetAnimID(EAnimState::Idle_Run); // Set Current Camera to Default State CurrentCameraState = DefaultCameraState; UpdateComponentsVisibility(); // Enable and start jetpack FillUp bCanFillJetPack = true; GetWorldTimerManager().SetTimer(JetPackHandle, this, &ARadeCharacter::JetPackFillUp, JumpJetPack.RestoreSpeed, true); }
void ACharacter::PostNetReceiveBase() { const bool bBaseChanged = (RelativeMovement.MovementBase != MovementBase); if (bBaseChanged) { SetBase(RelativeMovement.MovementBase); } if (RelativeMovement.HasRelativePosition()) { if (bBaseChanged || (RelativeMovement.Location != SavedRelativeLocation) || (RelativeMovement.Rotation != SavedRelativeRotation)) { const FVector OldLocation = GetActorLocation(); const FRotator NewRotation = (FRotationMatrix(RelativeMovement.Rotation) * FRotationMatrix(MovementBase->GetComponentRotation())).Rotator(); SetActorLocationAndRotation( MovementBase->GetComponentLocation() + RelativeMovement.Location, NewRotation, false); INetworkPredictionInterface* PredictionInterface = InterfaceCast<INetworkPredictionInterface>(GetMovementComponent()); if (PredictionInterface) { PredictionInterface->SmoothCorrection(OldLocation); } } } if ( CharacterMovement ) { CharacterMovement->bJustTeleported = false; } }
void ACharacter::PostNetReceiveLocation() { if( Role == ROLE_SimulatedProxy ) { // Don't change position if using relative position (it should be the same anyway) // TODO: actually we can't do this until SimulateMovement() actually calls UpdateBasedMovement(). //if (!RelativeMovement.HasRelativePosition()) { const FVector OldLocation = GetActorLocation(); UpdateSimulatedPosition(ReplicatedMovement.Location, ReplicatedMovement.Rotation); INetworkPredictionInterface* PredictionInterface = InterfaceCast<INetworkPredictionInterface>(GetMovementComponent()); if (PredictionInterface) { PredictionInterface->SmoothCorrection(OldLocation); } } } }
void APawn::PostNetReceiveLocationAndRotation() { // always consider Location as changed if we were spawned this tick as in that case our replicated Location was set as part of spawning, before PreNetReceive() if( (ReplicatedMovement.Location == GetActorLocation() && ReplicatedMovement.Rotation == GetActorRotation()) && (CreationTime != GetWorld()->TimeSeconds) ) { return; } if( Role == ROLE_SimulatedProxy ) { // Correction to make sure pawn doesn't penetrate floor after replication rounding ReplicatedMovement.Location.Z += 0.01f; const FVector OldLocation = GetActorLocation(); const FQuat OldRotation = GetActorQuat(); SetActorLocationAndRotation(ReplicatedMovement.Location, ReplicatedMovement.Rotation, /*bSweep=*/ false); INetworkPredictionInterface* PredictionInterface = Cast<INetworkPredictionInterface>(GetMovementComponent()); if (PredictionInterface) { PredictionInterface->SmoothCorrection(OldLocation, OldRotation, ReplicatedMovement.Location, ReplicatedMovement.Rotation.Quaternion()); } } }
const FNavAgentProperties& APawn::GetNavAgentPropertiesRef() const { UPawnMovementComponent* MovementComponent = GetMovementComponent(); return MovementComponent ? MovementComponent->GetNavAgentPropertiesRef() : FNavAgentProperties::DefaultProperties; }