// Sets default values AZombieCharacter::AZombieCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; //Initializing stats and components. AudioComponent = CreateDefaultSubobject<UAudioComponent>(FName("Audio")); AudioComponent->AttachTo(GetRootComponent()); ParticleSystemComponent = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ParticleComp")); ParticleSystemComponent->bAutoActivate = false; ParticleSystemComponent->AttachTo(GetRootComponent()); //Combat stats MinHealth = 100.f; MaxHealth = 300.f; MinSpeed = 150.f; MaxSpeed = 250.f; MinDamage = 5.f; MaxDamage = 15.f; DotTickInSeconds = 1.f; SlowPercentage = 0.5f; SlowEffectDuration = 3.f; Damage = 15.f; MeleeDistanceThreshold = 150.f; }
void ANimModCharacter::UpdateRunSounds(bool bNewRunning) { if (bNewRunning) { if (!RunLoopAC && RunLoopSound) { RunLoopAC = UGameplayStatics::PlaySoundAttached(RunLoopSound, GetRootComponent()); if (RunLoopAC) { RunLoopAC->bAutoDestroy = false; } } else if (RunLoopAC) { RunLoopAC->Play(); } } else { if (RunLoopAC) { RunLoopAC->Stop(); } if (RunStopSound) { UGameplayStatics::PlaySoundAttached(RunStopSound, GetRootComponent()); } } }
void AActor::EditorApplyScale( const FVector& DeltaScale, const FVector* PivotLocation, bool bAltDown, bool bShiftDown, bool bCtrlDown ) { if( RootComponent != NULL ) { const FVector CurrentScale = GetRootComponent()->RelativeScale3D; // @todo: Remove this hack once we have decided on the scaling method to use. if( AActor::bUsePercentageBasedScaling ) { GetRootComponent()->SetRelativeScale3D(CurrentScale + DeltaScale * CurrentScale); if (PivotLocation) { FVector Loc = GetActorLocation(); Loc -= *PivotLocation; Loc += DeltaScale * Loc; Loc += *PivotLocation; GetRootComponent()->SetWorldLocation(Loc); } } else { GetRootComponent()->SetRelativeScale3D(CurrentScale + DeltaScale * CurrentScale.GetSignVector()); } } else { UE_LOG(LogActor, Warning, TEXT("WARNING: EditorApplyTranslation %s has no root component"), *GetName() ); } FEditorSupportDelegates::UpdateUI.Broadcast(); }
AStick::AStick(){ RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent")); Stick = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("OurVisibleComponent")); Stick->SetMobility(EComponentMobility::Movable); Stick->CastShadow = false; Stick->AttachTo(RootComponent); UStaticMesh *mesh = nullptr; static ConstructorHelpers::FObjectFinder<UStaticMesh> MeshFinder(TEXT("StaticMesh'/Game/Models/Baculo/baculo_model.baculo_model'")); if (MeshFinder.Succeeded()){ mesh = MeshFinder.Object; Stick->SetStaticMesh(mesh); } Stick->SetWorldScale3D(FVector(0.75, 0.75, 0.75)); StickMaterial = ((UPrimitiveComponent*)GetRootComponent())->CreateAndSetMaterialInstanceDynamic(0); UMaterial* mat = nullptr; static ConstructorHelpers::FObjectFinder<UMaterial> MatFinder(TEXT("Material'/Game/Models/Baculo/baculo_diffuse.baculo_diffuse'")); if (MatFinder.Succeeded()){ mat = MatFinder.Object; StickMaterial = UMaterialInstanceDynamic::Create(mat, GetWorld()); } EffectsMaterial = ((UPrimitiveComponent*)GetRootComponent())->CreateAndSetMaterialInstanceDynamic(1); mat = nullptr; static ConstructorHelpers::FObjectFinder<UMaterial> MatFinderEffects(TEXT("Material'/Game/Models/Baculo/baculoBloom_material.baculoBloom_material'")); if (MatFinderEffects.Succeeded()){ mat = MatFinderEffects.Object; EffectsMaterial = UMaterialInstanceDynamic::Create(mat, GetWorld()); } BBMaterial = CreateDefaultSubobject<UMaterialBillboardComponent>(TEXT("BB")); BBMaterial->AttachTo(RootComponent); BBMaterial->SetMobility(EComponentMobility::Movable); BBMaterial->CastShadow = false; BBMaterial->SetRelativeLocation(FVector(0, 0, 70)); }
void ABxtAsteroidSpawner::SpawnAsteroid() { FActorSpawnParameters spawnParams; spawnParams.Owner = this; spawnParams.bDeferConstruction = true; const FVector spawnLocation = GetRandomSpawnLocation(); const FRotator spawnRotation = FRotator::ZeroRotator; auto asteroid = GetWorld()->SpawnActor<ABxtAsteroid>( AsteroidClass, spawnLocation, spawnRotation, spawnParams ); if (asteroid) { asteroid->SetInitialSpeed(AsteroidSpeed); asteroid->SetDirection(GetRandomSpawnDirection()); // preserve original root component scale const FVector spawnScale = GetRootComponent() ? GetRootComponent()->RelativeScale3D : FVector(1.0f, 1.0f, 1.0f); asteroid->FinishSpawning(FTransform(spawnRotation, spawnLocation, spawnScale), true); } }
// Sets default values ASmokePawn::ASmokePawn() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; AIControllerClass = ASmokeAIController::StaticClass(); collision = CreateDefaultSubobject<USphereComponent>(TEXT("SmokeCollision")); SetRootComponent(collision); collision->SetSimulatePhysics(true); collision->SetEnableGravity(false); collision->SetCollisionProfileName(FName("Pawn")); collision->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Overlap); smokeParticleSystem = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("SmokeParticle")); smokeParticleSystem->AttachTo(GetRootComponent()); ConstructorHelpers::FObjectFinder<UParticleSystem> particleAsset(TEXT("/Game/Particles/P_Smoke_AI")); smokeParticleSystem->SetTemplate(particleAsset.Object); movement = CreateDefaultSubobject<UFloatingPawnMovement>(TEXT("SmokeMovement")); movement->SetUpdatedComponent(GetRootComponent()); movement->MaxSpeed = 100.0f; movement->Acceleration = 100.0f; movement->Deceleration = 0.0; ConstructorHelpers::FObjectFinder<UBehaviorTree> behaviorAsset(TEXT("/Game/AI/SmokeBrain")); behavior = behaviorAsset.Object; }
void AActor::EditorApplyMirror(const FVector& MirrorScale, const FVector& PivotLocation) { const FRotationMatrix TempRot( GetActorRotation() ); const FVector New0( TempRot.GetScaledAxis( EAxis::X ) * MirrorScale ); const FVector New1( TempRot.GetScaledAxis( EAxis::Y ) * MirrorScale ); const FVector New2( TempRot.GetScaledAxis( EAxis::Z ) * MirrorScale ); // Revert the handedness of the rotation, but make up for it in the scaling. // Arbitrarily choose the X axis to remain fixed. const FMatrix NewRot( -New0, New1, New2, FVector::ZeroVector ); if( RootComponent != NULL ) { GetRootComponent()->SetRelativeRotation( NewRot.Rotator() ); FVector Loc = GetActorLocation(); Loc -= PivotLocation; Loc *= MirrorScale; Loc += PivotLocation; GetRootComponent()->SetRelativeLocation( Loc ); FVector Scale3D = GetRootComponent()->RelativeScale3D; Scale3D.X = -Scale3D.X; GetRootComponent()->SetRelativeScale3D(Scale3D); } else { UE_LOG(LogActor, Warning, TEXT("WARNING: EditorApplyMirror %s has no root component"), *GetName() ); } }
/** * Function that gets called from within Map_Check to allow this actor to check itself * for any potential errors and register them with map check dialog. */ void AVolume::CheckForErrors() { Super::CheckForErrors(); // The default physics volume can have zero area; it's extents aren't used, only the physics properties if (IsA(ADefaultPhysicsVolume::StaticClass())) { return; } if (GetRootComponent() == NULL) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Warning() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT( "MapCheck_Message_VolumeActorCollisionComponentNULL", "{ActorName} : Volume actor has NULL collision component - please delete" ), Arguments) )) ->AddToken(FMapErrorToken::Create(FMapErrors::VolumeActorCollisionComponentNULL)); } else { if (GetRootComponent()->Bounds.SphereRadius <= SMALL_NUMBER) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Warning() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT( "MapCheck_Message_VolumeActorZeroRadius", "{ActorName} : Volume actor has a collision component with 0 radius - please delete" ), Arguments) )); } } }
void AActor::CheckForErrors() { if ( GetClass()->HasAnyClassFlags(CLASS_Deprecated) ) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Warning() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT( "MapCheck_Message_ActorIsObselete_Deprecated", "{ActorName} : Obsolete and must be removed! (Class is deprecated)" ), Arguments) )) ->AddToken(FMapErrorToken::Create(FMapErrors::ActorIsObselete)); return; } if ( GetClass()->HasAnyClassFlags(CLASS_Abstract) ) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Warning() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT( "MapCheck_Message_ActorIsObselete_Abstract", "{ActorName} : Obsolete and must be removed! (Class is abstract)" ), Arguments) )) ->AddToken(FMapErrorToken::Create(FMapErrors::ActorIsObselete)); return; } UPrimitiveComponent* PrimComp = Cast<UPrimitiveComponent>(RootComponent); if( PrimComp && (PrimComp->Mobility != EComponentMobility::Movable) && PrimComp->BodyInstance.bSimulatePhysics) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Warning() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT( "MapCheck_Message_StaticPhysNone", "{ActorName} : Static object with bSimulatePhysics set to true" ), Arguments) )) ->AddToken(FMapErrorToken::Create(FMapErrors::StaticPhysNone)); } if( RootComponent && FMath::IsNearlyZero( GetRootComponent()->RelativeScale3D.X * GetRootComponent()->RelativeScale3D.Y * GetRootComponent()->RelativeScale3D.Z ) ) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Error() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT( "MapCheck_Message_InvalidDrawscale", "{ActorName} : Invalid DrawScale/DrawScale3D" ), Arguments) )) ->AddToken(FMapErrorToken::Create(FMapErrors::InvalidDrawscale)); } // Route error checking to components. TInlineComponentArray<UActorComponent*> Components; GetComponents(Components); for ( int32 ComponentIndex = 0 ; ComponentIndex < Components.Num() ; ++ComponentIndex ) { UActorComponent* ActorComponent = Components[ ComponentIndex ]; if (ActorComponent->IsRegistered()) { ActorComponent->CheckForErrors(); } } }
FVector APawn::GetVelocity() const { if(GetRootComponent() && GetRootComponent()->IsSimulatingPhysics()) { return GetRootComponent()->GetComponentVelocity(); } const UPawnMovementComponent* MovementComponent = GetMovementComponent(); return MovementComponent ? MovementComponent->Velocity : FVector::ZeroVector; }
void AActor::EditorApplyTranslation(const FVector& DeltaTranslation, bool bAltDown, bool bShiftDown, bool bCtrlDown) { if( RootComponent != NULL ) { GetRootComponent()->SetWorldLocation( GetRootComponent()->GetComponentLocation() + DeltaTranslation ); } else { UE_LOG(LogActor, Warning, TEXT("WARNING: EditorApplyTranslation %s has no root component"), *GetName() ); } }
/** Sets the current ball possessor */ void AMagicBattleSoccerBall::SetPossessor(AMagicBattleSoccerCharacter* Player) { if (Role < ROLE_Authority) { // Safety check. Only authority entities should drive the ball. } else { // We only allow a possession change if the ball is being unpossessed or the player is not one we're ignoring if (nullptr == Player || (CanPossessBall(Player) && (PossessorToIgnore != Player))) { AMagicBattleSoccerCharacter *OldPossessor = Possessor; // Assign the new possessor Possessor = Player; // Handle cases when the ball had a possessor in the previous frame if (nullptr != OldPossessor) { // Assign the last possessor LastPossessor = OldPossessor; // Assign the possessor to ignore PossessorToIgnore = OldPossessor; } // Toggle physics UPrimitiveComponent *Root = Cast<UPrimitiveComponent>(GetRootComponent()); if (nullptr != Possessor) { Possessor->StopWeaponFire(Possessor->PrimaryWeapon); Possessor->StopWeaponFire(Possessor->SecondaryWeapon); Root->PutRigidBodyToSleep(); Root->SetSimulatePhysics(false); Root->SetEnableGravity(false); SetActorEnableCollision(false); MoveWithPossessor(); } else { Root->SetSimulatePhysics(true); Root->SetEnableGravity(true); SetActorEnableCollision(true); Root->PutRigidBodyToSleep(); } } // Force the orientation to be replicated at the same time the possessor is replicated UPrimitiveComponent *Root = Cast<UPrimitiveComponent>(GetRootComponent()); ServerPhysicsState.pos = GetActorLocation(); ServerPhysicsState.rot = GetActorRotation(); ServerPhysicsState.vel = Root->GetComponentVelocity(); ServerPhysicsState.timestamp = AMagicBattleSoccerPlayerController::GetLocalTime(); } }
// Sets default values AAICharacter::AAICharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; BoxComp = CreateDefaultSubobject<UBoxComponent>(FName("BoxComp")); BoxComp->AttachTo(GetRootComponent()); AudioComp = CreateDefaultSubobject<UAudioComponent>(FName("AudioComp")); AudioComp->AttachTo(GetRootComponent()); }
class APhysicsVolume* APawn::GetPawnPhysicsVolume() const { const UPawnMovementComponent* MovementComponent = GetMovementComponent(); if (MovementComponent) { return MovementComponent->GetPhysicsVolume(); } else if (GetRootComponent()) { return GetRootComponent()->GetPhysicsVolume(); } return GetWorld()->GetDefaultPhysicsVolume(); }
void ALeapMotionHandActor::UpdateBones(float DeltaSeconds) { if (BoneActors.Num() == 0) { return; } float CombinedScale = GetCombinedScale(); FLeapMotionDevice* Device = FLeapMotionControllerPlugin::GetLeapDeviceSafe(); if (Device && Device->IsConnected()) { int BoneArrayIndex = 0; for (ELeapBone LeapBone = bShowArm ? ELeapBone::Forearm : ELeapBone::Palm; LeapBone <= ELeapBone::Finger4Tip; ((int8&)LeapBone)++) { FVector TargetPosition; FRotator TargetOrientation; bool Success = Device->GetBonePostionAndOrientation(HandId, LeapBone, TargetPosition, TargetOrientation); if (Success) { // Offset target position & rotation by the SpawnReference actor's transform FQuat RefQuat = GetRootComponent()->GetComponentRotation().Quaternion(); TargetPosition = RefQuat * TargetPosition * CombinedScale + GetRootComponent()->GetComponentLocation(); TargetOrientation = (RefQuat * TargetOrientation.Quaternion()).Rotator(); // Get current position & rotation ALeapMotionBoneActor* BoneActor = BoneActors[BoneArrayIndex++]; UPrimitiveComponent* PrimitiveComponent = Cast<UPrimitiveComponent>(BoneActor->GetRootComponent()); if (PrimitiveComponent && PrimitiveComponent->IsSimulatingPhysics()) { FVector CurrentPositon = PrimitiveComponent->GetComponentLocation(); FRotator CurrentRotation = PrimitiveComponent->GetComponentRotation(); // Compute linear velocity FVector LinearVelocity = (TargetPosition - CurrentPositon) / DeltaSeconds; // Compute angular velocity FVector Axis; float Angle; ConvertDeltaRotationsToAxisAngle(CurrentRotation, TargetOrientation, Axis, Angle); if (Angle > PI) { Angle -= 2 * PI; } FVector AngularVelcity = Axis * (Angle / DeltaSeconds); // Apply velocities PrimitiveComponent->SetPhysicsLinearVelocity(LinearVelocity); PrimitiveComponent->SetAllPhysicsAngularVelocity(AngularVelcity * 180.0f / PI); } } } } }
// Sets default values ASCharacter::ASCharacter(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; UCharacterMovementComponent* MoveComp = GetCharacterMovement(); // Adjust jump to make it less floaty MoveComp->GravityScale = 1.5f; MoveComp->JumpZVelocity = 620; MoveComp->bCanWalkOffLedgesWhenCrouching = true; MoveComp->MaxWalkSpeedCrouched = 200; /* Ignore this channel or it will absorb the trace impacts instead of the skeletal mesh */ GetCapsuleComponent()->SetCollisionResponseToChannel(COLLISION_WEAPON, ECR_Ignore); // Enable crouching MoveComp->GetNavAgentPropertiesRef().bCanCrouch = true; CameraBoomComp = ObjectInitializer.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("CameraBoom")); CameraBoomComp->SocketOffset = FVector(0, 35, 0); CameraBoomComp->TargetOffset = FVector(0, 0, 55); CameraBoomComp->bUsePawnControlRotation = true; CameraBoomComp->AttachParent = GetRootComponent(); CameraComp = ObjectInitializer.CreateDefaultSubobject<UCameraComponent>(this, TEXT("Camera")); CameraComp->AttachParent = CameraBoomComp; CarriedObjectComp = ObjectInitializer.CreateDefaultSubobject<USCarryObjectComponent>(this, TEXT("CarriedObjectComp")); CarriedObjectComp->AttachParent = GetRootComponent(); MaxUseDistance = 500; DropWeaponMaxDistance = 100; bHasNewFocus = true; TargetingSpeedModifier = 0.5f; SprintingSpeedModifier = 2.5f; Health = 100; IncrementHungerAmount = 5.0f; IncrementHungerInterval = 5.0f; CriticalHungerThreshold = 90; HungerDamagePerInterval = 1.0f; MaxHunger = 100; Hunger = 0; /* Names as specified in the character skeleton */ WeaponAttachPoint = TEXT("WeaponSocket"); PelvisAttachPoint = TEXT("PelvisSocket"); SpineAttachPoint = TEXT("SpineSocket"); }
void ACharacter::UpdateSimulatedPosition(const FVector& NewLocation, const FRotator& NewRotation) { // 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( (NewLocation != GetActorLocation()) || (CreationTime == GetWorld()->TimeSeconds) ) { FVector FinalLocation = NewLocation; // Only need to check for encroachment when teleported without any velocity. // Normal movement pops the character out of geometry anyway, no use doing it before and after (with different rules). bSimGravityDisabled = false; if (CharacterMovement->Velocity.IsZero()) { if (GetWorld()->EncroachingBlockingGeometry(this, NewLocation, NewRotation)) { bSimGravityDisabled = true; } } // Don't use TeleportTo(), that clears our base. SetActorLocationAndRotation(FinalLocation, NewRotation, false); CharacterMovement->bJustTeleported = true; } else if( NewRotation != GetActorRotation() ) { GetRootComponent()->MoveComponent(FVector::ZeroVector, NewRotation, false); } }
void AMech_RPGCharacter::SetUpWidgets() { if (widgetClass != nullptr) { floatingStats = CreateWidget<UFloatingStats_BP>(GetWorld(), widgetClass); floatingStats->SetOwner(this); stats->SetWidget(floatingStats); FTransform trans; trans.SetLocation(FVector(0.0, 8.0, 130.0)); trans.SetScale3D(FVector(0.25, 0.75, 1)); stats->SetRelativeTransform(trans); stats->AttachToComponent(GetRootComponent(), FAttachmentTransformRules(EAttachmentRule::SnapToTarget, false)); stats->SetDrawSize(FVector2D(100, 50)); //if (!isPlayer && !isAlly) { stats->SetVisibility(false, true); //} } if (inventory != nullptr) { int invSize = 20; inventory->SetMaxItemCount(invSize); /*inventory->AddItem(AItem::CreateItem(GetWorld(), this, "Item 1", 3, 0, 0, 5)); inventory->AddItem(AItem::CreateItem(GetWorld(), this, "Item 1", 3, 0, 0, 5)); inventory->AddItem(AItem::CreateItem(GetWorld(), this, "Item 2", 4, 0, 0, 2)); inventory->AddItem(AItem::CreateItem(GetWorld(), this, "Item 3", 0, 0, 0, 2)); inventory->AddItem(AItem::CreateItem(GetWorld(), this, "Item 4", 3, 0, 0, 1));*/ } GetFloatingStats()->UpdateHealthBar(); if (GetCharacterStats() != nullptr) { GetCharacterStats()->UpdateHealthBar(); } }
void AActor::DebugShowComponentHierarchy( const TCHAR* Info, bool bShowPosition ) { TArray<AActor*> ParentedActors; GetAttachedActors( ParentedActors ); if( Info ) { UE_LOG( LogActor, Warning, TEXT("--%s--"), Info ); } else { UE_LOG( LogActor, Warning, TEXT("--------------------------------------------------") ); } UE_LOG( LogActor, Warning, TEXT("--------------------------------------------------") ); UE_LOG( LogActor, Warning, TEXT("Actor [%x] (%s)"), this, *GetFName().ToString() ); USceneComponent* SceneComp = GetRootComponent(); if( SceneComp ) { int32 NestLevel = 0; DebugShowOneComponentHierarchy( SceneComp, NestLevel, bShowPosition ); } else { UE_LOG( LogActor, Warning, TEXT("Actor has no root.") ); } UE_LOG( LogActor, Warning, TEXT("--------------------------------------------------") ); }
AMagnetTile::AMagnetTile() : ATile() { PrimaryActorTick.bCanEverTick = true; ConstructorHelpers::FObjectFinder<UStaticMesh> mesh( *FName( "/Game/Models/Magnet" ).ToString() ); TileMesh->SetStaticMesh( mesh.Object ); TileMesh->SetMobility( EComponentMobility::Static ); BoxCollision->SetBoxExtent( FVector( 40.0f ) ); ConstructorHelpers::FObjectFinder<UParticleSystem> particle( *FName( "/Game/Particles/P_Magnet" ).ToString() ); magnetParticle = CreateDefaultSubobject<UParticleSystemComponent>( TEXT( "Magnet particle" ) ); magnetParticle->SetTemplate( particle.Object ); magnetParticle->AttachTo( GetRootComponent() ); magnetParticle->SetVisibility( false ); auto pc = Cast<UPrimitiveComponent>( RootComponent ); pc->SetWorldScale3D( FVector( 1.0f , 1.0f , 1.0f ) ); delegate.BindUFunction( this , TEXT( "OnBeginHit" ) ); BoxCollision->OnComponentHit.Add( delegate ); ConstructorHelpers::FObjectFinder<USoundWave> magnetSoundFile( TEXT( "/Game/Sound/S_MagnetLoop" ) ); magnetSound = CreateDefaultSubobject<UAudioComponent>( TEXT( "Magnet Sound" ) ); magnetSound->SetSound( magnetSoundFile.Object ); magnetSound->bAutoActivate = false; magnetSound->AttachTo( BoxCollision ); }
void ACharacter::UpdateSimulatedPosition(const FVector & NewLocation, const FRotator & NewRotation) { // 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( (NewLocation != GetActorLocation()) || (CreationTime == GetWorld()->TimeSeconds) ) { FVector FinalLocation = NewLocation; if( GetWorld()->EncroachingBlockingGeometry(this, NewLocation, NewRotation) ) { bSimGravityDisabled = true; } else { // Correction to make sure pawn doesn't penetrate floor after replication rounding FinalLocation.Z += 0.01f; bSimGravityDisabled = false; } // Don't use TeleportTo(), that clears our base. SetActorLocationAndRotation(FinalLocation, NewRotation, false); } else if( NewRotation != GetActorRotation() ) { GetRootComponent()->MoveComponent(FVector::ZeroVector, NewRotation, false); } }
// Sets default values ALaser::ALaser() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; root = CreateDefaultSubobject<UEmptyComponent>(TEXT("RootEmpty")); SetRootComponent(root); laserParticle = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("LaserParticle")); laserParticle->AttachTo(RootComponent); ConstructorHelpers::FObjectFinder<UParticleSystem> particleAssets(TEXT("/Game/Particles/P_NewLaser")); laserParticle->SetTemplate(particleAssets.Object); laserSparkParticle = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("LaserSparkParticle")); laserSparkParticle->AttachTo(RootComponent); ConstructorHelpers::FObjectFinder<UParticleSystem> particleSparkAssets(TEXT("/Game/Particles/P_LaserSparks")); laserSparkParticle->SetTemplate(particleSparkAssets.Object); mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("laser emitter")); mesh->AttachTo(RootComponent); ConstructorHelpers::FObjectFinder<UStaticMesh> laserEmitterMesh(TEXT("/Game/Models/TurretGun")); mesh->SetStaticMesh(laserEmitterMesh.Object); mesh->SetCastShadow(false); mesh->SetWorldScale3D(FVector(0.3f)); ConstructorHelpers::FObjectFinder<USoundWave> laserEmitSoundFile( TEXT( "/Game/Sound/S_LaserLoop" ) ); laserEmitSound = CreateDefaultSubobject<UAudioComponent>( TEXT( "Laser Emit Sound" ) ); laserEmitSound->SetSound( laserEmitSoundFile.Object ); laserEmitSound->AttachTo( GetRootComponent() ); }
void AZombieCharacter::Die() { //Disables the logic of the zombie and gradually destroys this Actor AZombieController* ZCon = Cast<AZombieController>(GetController()); if (ZCon) { //Increasing the kills and wave count if necessary OurCharacter->Kills++; URoguelikeGameInstance* GameInstance = Cast<URoguelikeGameInstance>(GetGameInstance()); GameInstance->IncreaseWaveCountIfNeeded(); OurCharacter->PlayerController->UpdateUI(); //Stopping the AI logic ZCon->UnPossess(); AlphaChannelReduction(); //AlphaReductionTimeline.PlayFromStart(); //Handling the last animations ZAnimInstance->bIsDead = true; ZAnimInstance->Speed = 0; AudioComponent->Stop(); //Disabling the collision to avoid false kill count! UCapsuleComponent* RootComp = Cast<UCapsuleComponent>(GetRootComponent()); RootComp->SetCollisionEnabled(ECollisionEnabled::NoCollision); } }
UDoNNavigationVolumeComponent* ADEPRECATED_VolumeAdaptiveBuilder::CreateNAVVolume(FVector Location, FName VolumeName, int32 SeedX, int32 SeedY, int32 SeedZ) { UDoNNavigationVolumeComponent* volumeComponent = NewObject<UDoNNavigationVolumeComponent>(this, UDoNNavigationVolumeComponent::StaticClass(), VolumeName); if (!volumeComponent) { FString counter = FString::Printf(TEXT("Could not generate NAV Volume %s at %s for seed x%d, y%d, z%d"), *VolumeName.ToString(), *Location.ToString(), SeedX, SeedY, SeedZ); UE_LOG(LogTemp, Log, TEXT("%s"), *counter); return NULL; } volumeComponent->SetWorldLocation(Location); volumeComponent->SetBoxExtent(FVector(0, 0, 0)); volumeComponent->X = SeedX; volumeComponent->Y = SeedY; volumeComponent->Z = SeedZ; //volumeComponent->bCreatedByConstructionScript = true; NAVVolumeComponents.Add(volumeComponent); volumeComponent->RegisterComponent(); volumeComponent->AttachTo(GetRootComponent(), NAME_None, EAttachLocation::KeepWorldPosition); return volumeComponent; }
void AActor::GatherCurrentMovement() { UPrimitiveComponent* RootPrimComp = Cast<UPrimitiveComponent>(GetRootComponent()); if (RootPrimComp && RootPrimComp->IsSimulatingPhysics()) { FRigidBodyState RBState; RootPrimComp->GetRigidBodyState(RBState); ReplicatedMovement.FillFrom(RBState); } else if(RootComponent != NULL) { // If we are attached, don't replicate absolute position if( RootComponent->AttachParent != NULL ) { // Networking for attachments assumes the RootComponent of the AttachParent actor. // If that's not the case, we can't update this, as the client wouldn't be able to resolve the Component and would detach as a result. if( AttachmentReplication.AttachParent != NULL ) { AttachmentReplication.LocationOffset = RootComponent->RelativeLocation; AttachmentReplication.RotationOffset = RootComponent->RelativeRotation; AttachmentReplication.RelativeScale3D = RootComponent->RelativeScale3D; } } else { ReplicatedMovement.Location = RootComponent->GetComponentLocation(); ReplicatedMovement.Rotation = RootComponent->GetComponentRotation(); ReplicatedMovement.LinearVelocity = GetVelocity(); ReplicatedMovement.bRepPhysics = false; } } }
// Sets default values AHealthPickup::AHealthPickup() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; //Initialization of components BoxComp = CreateDefaultSubobject<UBoxComponent>(FName("BoxComp")); SetRootComponent(BoxComp); HealthKitSM = CreateDefaultSubobject<UStaticMeshComponent>(FName("HealthKitSM")); ParticleSystemComp = CreateDefaultSubobject<UParticleSystemComponent>(FName("ParticleSystemComp")); ParticleSystemComp->AttachTo(GetRootComponent()); HealthKitSM->AttachTo(ParticleSystemComp); RotatingMovementComp = CreateDefaultSubobject<URotatingMovementComponent>(FName("RotatingMovementComp")); //Just an initial value HealthToProvide = 10.f; }
/** This occurs when play begins */ void AMagicBattleSoccerBall::BeginPlay() { Super::BeginPlay(); if (Role < ROLE_Authority) { // The server manages the game state; the soccer ball will be replicated to us. // Physics however are not replicated. We will need to have the ball orientation // replicated to us. We need to turn off physics simulation and collision detection. UPrimitiveComponent *Root = Cast<UPrimitiveComponent>(GetRootComponent()); Root->PutRigidBodyToSleep(); Root->SetSimulatePhysics(false); Root->SetEnableGravity(false); SetActorEnableCollision(false); } else { // Servers should add this soccer ball to the game mode cache. // It will get replicated to clients for when they need to access // the ball itself to get information such as who possesses it. AMagicBattleSoccerGameState* GameState = GetGameState(); GameState->SoccerBall = this; } }
void APawn::MoveIgnoreActorRemove(AActor* ActorToIgnore) { UPrimitiveComponent* RootPrimitiveComponent = Cast<UPrimitiveComponent>(GetRootComponent()); if( RootPrimitiveComponent ) { RootPrimitiveComponent->IgnoreActorWhenMoving(ActorToIgnore, false); } }
// Called every frame void AHunterProjectile::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); if (GetAttachParentActor()) { return; } FVector deltaMove = DeltaTime * m_velocity; FVector newLocation = GetActorLocation() + deltaMove; SetActorLocation(newLocation, false); AActor *hitActor = FindHitActor(); if (hitActor) { ABasicAIAgent *hitAgent = Cast<ABasicAIAgent>(hitActor); bool doAttach = false; UBoxComponent *attachBox = nullptr; if (hitAgent && hitAgent->m_teamID == TEAM_CALVES) { attachBox = hitAgent->GetSpearBox(); hitAgent->ModifyHealth(-m_projectileDamage); doAttach = true; } else if (ATP_TopDownCharacter *playerChar = Cast<ATP_TopDownCharacter>(hitActor)) { attachBox = playerChar->GetSpearBox(); playerChar->SpearHit(); doAttach = true; } if (attachBox) { FVector boxExtents = attachBox->GetScaledBoxExtent(); FVector boxOrigin = attachBox->GetComponentLocation(); FBox box(boxOrigin - boxExtents, boxOrigin + boxExtents); FVector attachPos = FMath::RandPointInBox(box); SetActorLocation(attachPos); } if (doAttach) { // Destroy(); SetLifeSpan(20.0f); GetRootComponent()->AttachTo(hitActor->GetRootComponent(), NAME_None, EAttachLocation::KeepWorldPosition); OnProjectileHit(); } } }
AWeaponEssentialsCharacter::AWeaponEssentialsCharacter(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { CurrentWeapon = NULL; Inventory.SetNum(3, false); // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // Set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; CollisionComp = ObjectInitializer.CreateDefaultSubobject<UBoxComponent>(this, "CollisionComp"); CollisionComp->AttachParent = GetRootComponent(); CollisionComp->OnComponentBeginOverlap.AddDynamic(this, &AWeaponEssentialsCharacter::OnCollision); // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = ObjectInitializer.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("CameraBoom")); CameraBoom->AttachParent = GetRootComponent(); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = ObjectInitializer.CreateDefaultSubobject<UCameraComponent>(this, TEXT("FollowCamera")); FollowCamera->AttachTo(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm /* Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) * are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) */ }