キャストのクイックスタート ガイド

キャスト通信メソッドのクイックスタート

実装方法を選んでください。

Blueprints

C++

概要

キャスティングとは、アクタへの参照を取得して、それを別のクラスに変換しようとする際、一般的に使用される通信方法です。変換が成功すると、直接アクタ通信を使って情報や関数にアクセスすることができるようになります。 この方法では、Cast ノードを使用して特定のクラスに変換しようとするため、レベル内のアクタへの参照が必要になります。この通信方法では、作業アクタとターゲット アクタ間で 1 対 1 の関係を使用します。

設定

  1. [Games (ゲーム)] > [Third Person (サードパーソン)] > [Blueprint] の順に選択して、BPCommunication という名前のプロジェクトを作成します。

    ProjectSetupBp.png

回転アクタの作成

この例では、プレイヤーが近くにいるときにスタティック メッシュの回転を開始するアクタを作成します。

  1. コンテンツ ブラウザ を右クリックして、[Create Basic Asset (基本アセットの作成)] セクション内の [Blueprint Class (ブループリント クラス)] をクリックします。

    BlueprintClass.png

  2. [Actor (アクタ)] を親クラスとして選択し、ブループリントに「BP_RotateActor」という名前を付けます。

    ParentClassActor.png

  3. コンテンツ ブラウザ 内のブループリントをダブルクリックして開きます。ブループリント エディタ ウィンドウの [Components (コンポーネント)] パネルで [Add Component (コンポーネントを追加)] ボタンをクリックします。Static Mesh を検索して選択します。ブループリントに、Static Mesh コンポーネントが追加されます。

    ![]StaticMesh.png)

  4. Static Mesh コンポーネントを選択した状態で [Details (詳細)] パネルに移動し、ドロップダウンの [Static Mesh (スタティック メッシュ)] をクリックします。Shape_Cube を検索して選択します。

    StaticMeshDetails.png

  5. [Event Graph (イベント グラフ)] 内で右クリックして状況依存検索ウィンドウを開き、AddActorLocalRotation を検索、選択して、このノードをグラフに追加します。

    AddActorLocalRotation.png

  6. AddActorLocalRotation ノードを [Event Tick (イベント ティック)] に接続します。Z の値を「2.0」に設定します。

    AddActorLocalRotationZ.png

  7. ブループリントを コンパイル して 保存 します。

  8. Drag the BP_RotateActor Actor into the Level and press Play.すると回転し続ける立方体が表示されるはずです。

    DragRotatingCube.png

  9. それでは、プレイヤーが近くにいるときだけオブジェクトが回転するような条件を追加しましょう。イベント グラフ を右クリックして Branch ノードを追加します。Event Tick の出力ピンと AddActorLocalRotation ノードの入力ピンの間にノードを接続します。

    BranchNode.png

  10. Can Rotate という名前のブーリアン変数タイプを作成し、下に示すような Branch ノードの Condition ピンに接続します。

    BranchCanRotate.png

  11. ブループリントを コンパイル し、CanRotate のデフォルト値を False にします。

    DefaultRotateFalse.png

  12. [My Blueprint (マイ ブループリント)] タブに移動し、[+ Function] ボタンをクリックして新しい関数を作成します。関数名を OverlappedPlayer** にします。

    OverlappedPlayerFunction.png

  13. その関数を選択した状態で [Details] パネルに移動し、[+ New Parameter] ボタンをクリックします。新しいブーリアン パラメータ名を Begin Overlap にします。

    BeginOverlapInput.png

  14. [CanRotate] 変数を関数の中にドラッグして [Set CanRotate] を選択します。Overlapped Player ノードを Set Can Rotate ノードに接続します。Overlapped Player ノードの Begin Overlap ピンを、下のように Set Can Rotate ノードの Can Rotate ピンに接続します。

    ConnectCanRotate.png

  15. ブループリントを コンパイル して 保存 します。

プレイヤー ブループリントを変更する

このセクションでは、ThirdPersonCharacter ブループリントを変更して BP_RotateActor アクタにキャスティングし、プレイヤーが近くにいるときに Rotate 変数を True に設定します。

  1. ThirdPersonCharacter ブループリントを開きます。

  2. ブループリント エディタ ウィンドウの [Components (コンポーネント)] パネルで [Add Component (コンポーネントを追加)] ボタンをクリックします。Sphere Collision を検索して選択します。ブループリントに、Sphere Collision コンポーネントが追加されます。

    SphereCollision.png

  3. Sphere Collision コンポーネントが選択された状態で[Details (詳細)] パネルに移動し、[Radius (半径)] の値を 200 に設定します。

    SphereRadius.png

  4. Sphere Collision コンポーネントを右クリックして OnComponentBeginOverlap イベントと OnComponentEndOverlap イベントを選択し、これらを イベント グラフ に追加します。

    OverlapEvents.png

    OverlapEventNodes.png

  5. On Component Begin Overlap ノードの [Other Actor (その他のアクタ)] ピンからドラッグし、cast to BP Rotate Object を検索して選択します。

    CastToBpRotateActor.png

  6. As BP Rotate Object ピンからドラッグして、Overlapped Player を検索、選択します。Overlapped Player ノードの Begin Overlap ピンを有効化します。

    OverlappedPlayer.png

    OverlappedPlayerWhole.png

  7. 手順 5 と 6 を繰り返して、同じノードを On Component End Overlap ノードにアタッチします。Overlapped Player ノードの Begin Overlap ピンを無効化します。

    CompleteFunction.png

  8. ブループリントを コンパイル して 保存 します。

  9. [Play (プレイ)] を押して BP_RotateActor アクタに近づいたときのみ、それが回転するかどうか確認します。

    RotateCube.gif

次のステップ

キャスティングの使い方が分かったところで、今度は「アクタ通信」ドキュメント ページで参照されている他の通信手段を見てみましょう。

概要

ブループリント クラスのキャスティングは、アクタ クラス ブループリントへの参照を使用して、それを別のクラスに変換する際、一般的に使用される通信方法です。変換が成功すると、直接ブループリント通信を使って情報や関数にアクセスすることができるようになります。

この方法では、Cast ノードを使用して特定のクラスに変換しようとするため、レベル内のアクタ クラス ブループリントへの参照が必要になります。この通信方法では、作業アクタ クラス ブループリントとターゲット アクタ クラス ブループリント間で 1 対 1 の関係を使用します。

このクイック スタート ガイドでは、ターゲット ブループリントから情報にアクセスするために使用するブループリント キャスティング機能を備えたアクタを C++ で作成する方法を学習します。

設定

  1. [Games (ゲーム)] > [Third Person (サードパーソン)] > [C++] の順に選択して、BPCommunication** という名前のプロジェクトを作成します。

    ProjectSetupCpp.png

回転アクタの作成

この例では、プレイヤーが近くにいるときにスタティック メッシュ コンポーネントの回転を開始する関数を備えたアクタ クラス ブループリントを作成します。

  1. C++ クラス ウィザード から、新規アクタクラスを「RotatingActor」という名前で作成します。

    AddCppClass.png

  2. RotatingActor.h」のクラス デフォルトで、以下のコードを実装します。

        public:
    
            void SetbCanRotate(bool value);
    
            protected:
    
            // ゲームが開始またはスポーンされた時に呼び出されます。
            virtual void BeginPlay() override;
            void RotateActor();
            bool bCanRotate;
    
            UPROPERTY(EditAnywhere, BlueprintReadWrite)
            UStaticMeshComponent* MeshComp;
  3. RotatingActor.cpp」に移動し、コンストラクタの ARotatingActor::ARotatingActor 内で次のコードを宣言します。

    ARotatingActor::ARotatingActor()
    {
        RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"));
        MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
        MeshComp->SetupAttachment(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
        bCanRotate = false;
    }
  4. ARotatingActor::RotateActor メソッドで次のコードを実装します。

    void ARotatingActor::RotateActor()
    {
        AddActorLocalRotation(ActorRotation);
    }
  5. ARotatingActor::Tick メソッドに移動し、以下のコードを実装します。

    void ARotatingActor::Tick(float DeltaTime)
        {
            Super::Tick(DeltaTime);
    
            if (bCanRotate)
            {
                RotateActor();
            }
        }

完成コード

RotatingActor.h

    #pragma once
    #include "CoreMinimal.h"
    #include "GameFramework/Actor.h"
    #include "RotatingActor.generated.h"

    UCLASS()
    class BPCOMMUNICATION_API ARotatingActor : public AActor
    {
    GENERATED_BODY()

    public:
        // このアクタのプロパティにデフォルト値を設定します。
        ARotatingActor();
        void SetbCanRotate(bool value);

    protected:
        // ゲームが開始またはスポーンされた時に呼び出されます。
        virtual void BeginPlay() override;
        void RotateActor();
        bool bCanRotate;

        UPROPERTY(EditAnywhere, BlueprintReadWrite)
        UStaticMeshComponent* MeshComp;

        //アクタの回転率。
        const FQuat ActorRotationRate =(FQuat(FRotator(0,2,0));

    public:
        // フレームごとに呼び出されます。
        virtual void Tick(float DeltaTime) override;
    };

RotatingActor.cpp

    #include "RotatingActor.h"

    // デフォルト値を設定します
    ARotatingActor::ARotatingActor()
    {
        // フレームごとに Tick() を呼び出すようにこのアクタを設定します。不要な場合はオフにすることで性能を向上させることができます。
        PrimaryActorTick.bCanEverTick = true;
        RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"));
        MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp"));
        MeshComp->SetupAttachment(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
        bCanRotate = false;
    }

    void ARotatingActor::SetbCanRotate(bool value)
    {
        bCanRotate = value;
    }

    // ゲームが開始またはスポーンされた時に呼び出されます。
    void ARotatingActor::BeginPlay()
    {
        Super::BeginPlay();
    }

    void ARotatingActor::RotateActor()
    {
        AddActorLocalRotation(ActorRotation);
    }

    // フレームごとに呼び出されます。
    void ARotatingActor::Tick(float DeltaTime)
    {
        Super::Tick(DeltaTime);

        if (bCanRotate)
        {
            RotateActor();
        }
    }
  1. コードを コンパイル します。

  2. エディタで、「C++ Classes」フォルダに移動し、[C++ class actions (C++ クラス アクション)] ドロップダウンメニューから RotatingActor を右クリックし、「BP_RotatingActor」という名前の [Create Blueprint class based on RotatingActor] を選択します。

    BpRotateActor.png

  3. BP_RotatingActor ブループリントの [Class Defaults (クラスのデフォルト)] で [Components] タブに移動し、MeshComp Static Mesh Component を選択します。次に、[Static Mesh] カテゴリから [Details (詳細)] パネルに移動し、Static Mesh 変数の隣にある矢印を選択します。最後に、ドロップダウン メニューから Shape_Cube スタティック メッシュを選択します。

    StaticMeshDetails.png

  4. ブループリントを コンパイル して 保存 します。

  5. コンテンツ ブラウザ から、Bp_RotatingActor のインスタンスをレベルにドラッグします。

    DragRotatingCube.png

サードパーソン キャラクター クラスを変更する

このセクションでは、BPCommunicationCharacter クラスを変更して Rotating Actor クラスにキャスティングし、プレイヤーが近くにいるときに bCanRotate 変数を True に設定します

  1. BPCommunicationCharacter.h」を開き、以下を実装します。

        protected:
            virtual void NotifyActorBeginOverlap(AActor* OtherActor);
            virtual void NotifyActorEndOverlap(AActor* OtherActor);
            class USphereComponent* SphereComp;

1.「BPCommunicationCharacter.cpp 」で、以下のクラス ライブラリを含めます。

    #include "RotatingActor.h"
    #include "Components/SphereComponent.h"
  1. コンストラクタの ABPCommunicaionCharacter::BPCommunicationCharacter から、以下のコードを宣言します。

        SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
        SphereComp->AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform);
        SphereComp->SetSphereRadius(200);
  2. 次に、ABPCommunicationCharacter::NotifyActorBeginOverlapABPCommunicationCharacter::NotifyActorEndOverlap を実装します。

        void ABPCommunicationCharacter::NotifyActorBeginOverlap(AActor* OtherActor)
        {
            if (ARotatingActor* RotatingActorCheck =Cast<ARotatingActor>(OtherActor))
            {
                ActorCheck->SetbCanRotate(true);
            }
        }
    
        void ABPCommunicationCharacter::NotifyActorEndOverlap(AActor* OtherActor)
        {
            if (ARotatingActor* RotatingActorCheck = Cast<ARotatingActor>(OtherActor))
            {
                ActorCheck->SetbCanRotate(false);
            }
        }
  3. コードを コンパイル します。

完成コード

BpCommunicationCharacter.h

    // Copyright Epic Games, Inc.All Rights Reserved.
    #pragma once
    #include "CoreMinimal.h"
    #include "GameFramework/Character.h"
    #include "BPCommunicationCharacter.generated.h"

    UCLASS(config=Game)
    class ABPCommunicationCharacter : public ACharacter
    {
        GENERATED_BODY()

        /** Camera boom positioning the camera behind the character */
        UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
        class USpringArmComponent* CameraBoom;

        /** Follow camera */
        UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
        class UCameraComponent* FollowCamera;

        public:
            ABPCommunicationCharacter();

            /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */
            UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
            float BaseTurnRate;

            /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */
            UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
            float BaseLookUpRate;

        protected:
            virtual void NotifyActorBeginOverlap(AActor* OtherActor);
            virtual void NotifyActorEndOverlap(AActor* OtherActor);

        UPROPERTY(EditAnywhere, BlueprintReadWrite)

            class USphereComponent* SphereComp;

            /** Resets HMD orientation in VR. */
            void OnResetVR();

            /** Called for forwards/backward input */
            void MoveForward(float Value);

            /** Called for side to side input */
            void MoveRight(float Value);

            /**
             * Called via input to turn at a given rate.
             * @param Rate  This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
             */
            void TurnAtRate(float Rate);

            /**
             * Called via input to turn look up/down at a given rate.
             * @param Rate  This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
             */
            void LookUpAtRate(float Rate);

            /** Handler for when a touch input begins. */
            void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location);

            /** Handler for when a touch input stops. */
            void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location);

        protected:
            // APawn インターフェース
            virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
            // APawn インターフェースの終わり

        public:
            /** Returns CameraBoom subobject **/
            FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; }

            /** Returns FollowCamera subobject **/
            FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; }
    };

BpCommunication.cpp

    // Copyright Epic Games, Inc. All Rights Reserved.
    #include "BPCommunicationCharacter.h"
    #include "HeadMountedDisplayFunctionLibrary.h"
    #include "Camera/CameraComponent.h"
    #include "Components/CapsuleComponent.h"
    #include "Components/InputComponent.h"
    #include "GameFramework/CharacterMovementComponent.h"
    #include "GameFramework/Controller.h"
    #include "GameFramework/SpringArmComponent.h"
    #include "CeilingLight.h"
    #include "RotatingActor.h"
    #include "Components/SphereComponent.h"

    //////////////////////////////////////////////////////////////////////////
    // ABPCommunicationCharacter

    ABPCommunicationCharacter::ABPCommunicationCharacter()
    {
        // コリジョンカプセルのサイズを設定する
        GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);

        // 入力のターン率を設定します
        BaseTurnRate = 45.f;
        BaseLookUpRate = 45.f;

        // コントローラーが回転するときに回転しないでください。Let that just affect the camera.
        bUseControllerRotationPitch = false;
        bUseControllerRotationYaw = false;
        bUseControllerRotationRoll = false;

        // カメラの移動を構成します
        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;

        // カメラブームを作成します (コリジョンがある場合プレイヤーに引き寄せられます)
        CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
        CameraBoom->SetupAttachment(RootComponent);
        CameraBoom->TargetArmLength = 300.0f; // カメラはこの距離でキャラクターの後ろを追従します
        CameraBoom->bUsePawnControlRotation = true; // コントローラーに基づいて腕を回転します

        // 追従カメラを作成します
        FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
        FollowCamera->SetupAttachment(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

        SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
        SphereComp->SetupAttachment(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform);
        SphereComp->SetSphereRadius(200);

        // 注:メッシュコンポーネントのスケルタルメッシュとアニメーションブループリントの参照 (キャラクターから継承)
        // MyCharacter という名前の派生ブループリントアセットに設定されます (C++ で直接コンテンツを参照しないようにするため)
    }

    //////////////////////////////////////////////////////////////////////////
    // 入力

    void ABPCommunicationCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
    {
        // ゲームプレイ キー バインディングを設定する
        check(PlayerInputComponent);
        PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
        PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
        PlayerInputComponent->BindAction("Use", IE_Pressed, this, &ABPCommunicationCharacter::ToggleCeilingLight);
        PlayerInputComponent->BindAxis("MoveForward", this, &ABPCommunicationCharacter::MoveForward);
        PlayerInputComponent->BindAxis("MoveRight", this, &ABPCommunicationCharacter::MoveRight);

        // 回転バインディングを 2 種類用意し、異なる種類のデバイスに対応できるようにしました。
        // "turn" は、マウスのような絶対的なデルタを提供するデバイスを扱います。
        // "turnrate"は、アナログジョイスティックのような変化率として扱うことを選択したデバイスのためのものです
        PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
        PlayerInputComponent->BindAxis("TurnRate", this, &ABPCommunicationCharacter::TurnAtRate);
        PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
        PlayerInputComponent->BindAxis("LookUpRate", this, &ABPCommunicationCharacter::LookUpAtRate);

        // ハンドル タッチ デバイス
        PlayerInputComponent->BindTouch(IE_Pressed, this, &ABPCommunicationCharacter::TouchStarted);
        PlayerInputComponent->BindTouch(IE_Released, this, &ABPCommunicationCharacter::TouchStopped);

        // VR ヘッドセット機能
        PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ABPCommunicationCharacter::OnResetVR);
    }

    void ABPCommunicationCharacter::NotifyActorBeginOverlap(AActor* OtherActor)
    {
        if (ARotatingActor* RotatingActorCheck =Cast<ARotatingActor>(OtherActor))
        {
            ActorCheck->SetbCanRotate(true);
        }
    }

    void ABPCommunicationCharacter::NotifyActorEndOverlap(AActor* OtherActor)
    {
        if (ARotatingActor* RotatingActorCheck = Cast<ARotatingActor>(OtherActor))
        {
            ActorCheck->SetbCanRotate(false);
        }
    }

    void ABPCommunicationCharacter::OnResetVR()
    {
        // BPCommunication を Unreal Editor の 'Add Feature' でプロジェクトに追加した場合、BPCommunication.Build.cs の HeadMountedDisplay の依存関係が自動的に伝播されず、
        // リンカーエラーが発生することがある。

        // 以下のいずれかを行う必要があります。
        //      "HeadMountedDisplay" を [YourProject].Build.cs PublicDependencyModuleNames に追加して正常にビルドを行う (VR をサポートする場合は適切)。
        // または
        //      以下の ResetOrientationAndPosition の呼び出しをコメントまたは削除する (VR をサポートしない場合は適切)。

        UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
    }

    void ABPCommunicationCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
    {
            Jump();
    }

        void ABPCommunicationCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
    {
            StopJumping();
    }

        void ABPCommunicationCharacter::TurnAtRate(float Rate)
    {
        // レート情報からこのフレームのデルタを計算します
        AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
    }

    void ABPCommunicationCharacter::LookUpAtRate(float Rate)
    {
        // レート情報からこのフレームのデルタを計算します
        AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
    }

    void ABPCommunicationCharacter::MoveForward(float Value)
    {
        if ((Controller != nullptr) && (Value != 0.0f))
        {
            // 前方を見つけます
            const FRotator Rotation = Controller->GetControlRotation();
            const FRotator YawRotation(0, Rotation.Yaw, 0);

            // 前方ベクターを取得します
            const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
            AddMovementInput(Direction, Value);
        }
    }

        void ABPCommunicationCharacter::MoveRight(float Value)
    {
        if ( (Controller != nullptr) && (Value != 0.0f) )
        {
            // 右側を見つけます
            const FRotator Rotation = Controller->GetControlRotation();
            const FRotator YawRotation(0, Rotation.Yaw, 0);
            // 右ベクターを取得します

            const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);

            // その方向に移動を追加します
            AddMovementInput(Direction, Value);
        }
    }
  1. [Play (プレイ)] を押して BP_RotateActor アクタに近づいたときのみ、それが回転するかどうか確認します。

    RotateCube.gif

次のステップ

ブループリント キャスティングの使い方が分かったところで、今度は「アクタ通信」ドキュメント ページで参照されている他の通信手段を見てみましょう。

このページは Unreal Engine の前のバージョン用です。現在リリースされている Unreal Engine 5.3 に対して更新は行われていません。
Unreal Engine のドキュメントを改善するために協力をお願いします!どのような改善を望んでいるかご意見をお聞かせください。
調査に参加する
キャンセル