概要
キャスティングとは、アクタへの参照を取得して、それを別のクラスに変換しようとする際、一般的に使用される通信方法です。変換が成功すると、直接アクタ通信を使って情報や関数にアクセスすることができるようになります。
この方法では、Cast ノードを使用して特定のクラスに変換しようとするため、レベル内のアクタへの参照が必要になります。この通信方法では、作業アクタとターゲット アクタ間で 1 対 1 の関係を使用します。
設定
-
[Games (ゲーム)] > [Third Person (サードパーソン)] > [Blueprint] の順に選択して、BPCommunication という名前のプロジェクトを作成します。
回転アクタの作成
この例では、プレイヤーが近くにいるときにスタティック メッシュの回転を開始するアクタを作成します。
-
コンテンツ ブラウザ を右クリックして、[Create Basic Asset (基本アセットの作成)] セクション内の [Blueprint Class (ブループリント クラス)] をクリックします。
-
[Actor (アクタ)] を親クラスとして選択し、ブループリントに「BP_RotateActor」という名前を付けます。
-
コンテンツ ブラウザ 内のブループリントをダブルクリックして開きます。ブループリント エディタ ウィンドウの [Components (コンポーネント)] パネルで [Add Component (コンポーネントを追加)] ボタンをクリックします。Static Mesh を検索して選択します。ブループリントに、Static Mesh コンポーネントが追加されます。
![]StaticMesh.png)
-
Static Mesh コンポーネントを選択した状態で [Details (詳細)] パネルに移動し、ドロップダウンの [Static Mesh (スタティック メッシュ)] をクリックします。Shape_Cube を検索して選択します。
-
[Event Graph (イベント グラフ)] 内で右クリックして状況依存検索ウィンドウを開き、AddActorLocalRotation を検索、選択して、このノードをグラフに追加します。
-
AddActorLocalRotation ノードを [Event Tick (イベント ティック)] に接続します。Z の値を「2.0」に設定します。
-
ブループリントを コンパイル して 保存 します。
-
Drag the BP_RotateActor Actor into the Level and press Play.すると回転し続ける立方体が表示されるはずです。
-
それでは、プレイヤーが近くにいるときだけオブジェクトが回転するような条件を追加しましょう。イベント グラフ を右クリックして Branch ノードを追加します。Event Tick の出力ピンと AddActorLocalRotation ノードの入力ピンの間にノードを接続します。
-
Can Rotate という名前のブーリアン変数タイプを作成し、下に示すような Branch ノードの Condition ピンに接続します。
-
ブループリントを コンパイル し、CanRotate のデフォルト値を False にします。
-
[My Blueprint (マイ ブループリント)] タブに移動し、[+ Function] ボタンをクリックして新しい関数を作成します。関数名を OverlappedPlayer** にします。
-
その関数を選択した状態で [Details] パネルに移動し、[+ New Parameter] ボタンをクリックします。新しいブーリアン パラメータ名を Begin Overlap にします。
-
[CanRotate] 変数を関数の中にドラッグして [Set CanRotate] を選択します。Overlapped Player ノードを Set Can Rotate ノードに接続します。Overlapped Player ノードの Begin Overlap ピンを、下のように Set Can Rotate ノードの Can Rotate ピンに接続します。
-
ブループリントを コンパイル して 保存 します。
プレイヤー ブループリントを変更する
このセクションでは、ThirdPersonCharacter ブループリントを変更して BP_RotateActor アクタにキャスティングし、プレイヤーが近くにいるときに Rotate 変数を True に設定します。
- ThirdPersonCharacter ブループリントを開きます。
- ブループリント エディタ ウィンドウの [Components (コンポーネント)] パネルで [Add Component (コンポーネントを追加)] ボタンをクリックします。Sphere Collision を検索して選択します。ブループリントに、Sphere Collision コンポーネントが追加されます。

-
Sphere Collision コンポーネントが選択された状態で[Details (詳細)] パネルに移動し、[Radius (半径)] の値を 200 に設定します。
-
Sphere Collision コンポーネントを右クリックして OnComponentBeginOverlap イベントと OnComponentEndOverlap イベントを選択し、これらを イベント グラフ に追加します。
-
On Component Begin Overlap ノードの [Other Actor (その他のアクタ)] ピンからドラッグし、cast to BP Rotate Object を検索して選択します。
-
As BP Rotate Object ピンからドラッグして、Overlapped Player を検索、選択します。Overlapped Player ノードの Begin Overlap ピンを有効化します。
-
手順 5 と 6 を繰り返して、同じノードを On Component End Overlap ノードにアタッチします。Overlapped Player ノードの Begin Overlap ピンを無効化します。
-
ブループリントを コンパイル して 保存 します。
-
[Play (プレイ)] を押して BP_RotateActor アクタに近づいたときのみ、それが回転するかどうか確認します。
(w:600)(convert:false)
次のステップ
キャスティングの使い方が分かったところで、今度は「アクタ通信」ドキュメント ページで参照されている他の通信手段を見てみましょう。
概要
ブループリント クラスのキャスティングは、アクタ クラス ブループリントへの参照を使用して、それを別のクラスに変換する際、一般的に使用される通信方法です。変換が成功すると、直接ブループリント通信を使って情報や関数にアクセスすることができるようになります。
この方法では、Cast ノードを使用して特定のクラスに変換しようとするため、レベル内のアクタ クラス ブループリントへの参照が必要になります。この通信方法では、作業アクタ クラス ブループリントとターゲット アクタ クラス ブループリント間で 1 対 1 の関係を使用します。
このクイック スタート ガイドでは、ターゲット ブループリントから情報にアクセスするために使用するブループリント キャスティング機能を備えたアクタを C++ で作成する方法を学習します。
設定
-
[Games (ゲーム)] > [Third Person (サードパーソン)] > [C++] の順に選択して、BPCommunication** という名前のプロジェクトを作成します。
回転アクタの作成
この例では、プレイヤーが近くにいるときにスタティック メッシュ コンポーネントの回転を開始する関数を備えたアクタ クラス ブループリントを作成します。
-
C++ クラス ウィザード から、新規アクタクラスを「RotatingActor」という名前で作成します。
-
「RotatingActor.h」のクラス デフォルトで、以下のコードを実装します。
public: void SetbCanRotate(bool value); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; void RotateActor(); bool bCanRotate; UPROPERTY(EditAnywhere, BlueprintReadWrite) UStaticMeshComponent* MeshComp; -
Navigate to your RotatingActor.cpp and declare the following code in the constructor ARotatingActor::ARotatingActor
ARotatingActor::ARotatingActor() { RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent")); MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh")); MeshComp->SetupAttachment(RootComponent, FAttachmentTransformRules::KeepRelativeTransform); bCanRotate = false; } -
Implement the following code for your ARotatingActor::RotateActor method.
void ARotatingActor::RotateActor() { AddActorLocalRotation(ActorRotation); } -
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:
// Sets default values for this actor's properties
ARotatingActor();
void SetbCanRotate(bool value);
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
void RotateActor();
bool bCanRotate;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UStaticMeshComponent* MeshComp;
//Rotation Rate for our Actor.
const FQuat ActorRotationRate =(FQuat(FRotator(0,2,0));
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
RotatingActor.cpp
#include "RotatingActor.h"
// Sets default values
ARotatingActor::ARotatingActor()
{
// 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;
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"));
MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp"));
MeshComp->SetupAttachment(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
bCanRotate = false;
}
void ARotatingActor::SetbCanRotate(bool value)
{
bCanRotate = value;
}
// Called when the game starts or when spawned
void ARotatingActor::BeginPlay()
{
Super::BeginPlay();
}
void ARotatingActor::RotateActor()
{
AddActorLocalRotation(ActorRotation);
}
// Called every frame
void ARotatingActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (bCanRotate)
{
RotateActor();
}
}
-
コードを コンパイル します。
-
エディタで、「C++ Classes」フォルダに移動し、[C++ class actions (C++ クラス アクション)] ドロップダウンメニューから RotatingActor を右クリックし、「BP_RotatingActor」という名前の [Create Blueprint class based on RotatingActor] を選択します。
-
BP_RotatingActor ブループリントの [Class Defaults (クラスのデフォルト)] で [Components] タブに移動し、MeshComp Static Mesh Component を選択します。次に、[Static Mesh] カテゴリから [Details (詳細)] パネルに移動し、Static Mesh 変数の隣にある矢印を選択します。最後に、ドロップダウン メニューから Shape_Cube スタティック メッシュを選択します。
-
ブループリントを コンパイル して 保存 します。
-
コンテンツ ブラウザ から、Bp_RotatingActor のインスタンスをレベルにドラッグします。
サードパーソン キャラクター クラスを変更する
このセクションでは、BPCommunicationCharacter クラスを変更して Rotating Actor クラスにキャスティングし、プレイヤーが近くにいるときに bCanRotate 変数を True に設定します
-
「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"
-
コンストラクタの ABPCommunicaionCharacter::BPCommunicationCharacter から、以下のコードを宣言します。
SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp")); SphereComp->AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform); SphereComp->SetSphereRadius(200); -
次に、ABPCommunicationCharacter::NotifyActorBeginOverlap と ABPCommunicationCharacter::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); } } -
コードを コンパイル します。
完成コード
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 interface
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// End of APawn interface
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()
{
// 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;
// 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 = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
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 = 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);
// 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++)
}
//////////////////////////////////////////////////////////////////////////
// Input
void ABPCommunicationCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// Set up gameplay key bindings
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);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &ABPCommunicationCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &ABPCommunicationCharacter::LookUpAtRate);
// handle touch devices
PlayerInputComponent->BindTouch(IE_Pressed, this, &ABPCommunicationCharacter::TouchStarted);
PlayerInputComponent->BindTouch(IE_Released, this, &ABPCommunicationCharacter::TouchStopped);
// VR headset functionality
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()
{
// If BPCommunication is added to a project via 'Add Feature' in the Unreal Editor the dependency on HeadMountedDisplay in BPCommunication.Build.cs is not automatically propagated
// and a linker error will result.
// You will need to either:
// Add "HeadMountedDisplay" to [YourProject].Build.cs PublicDependencyModuleNames in order to build successfully (appropriate if supporting VR).
// or:
// Comment or delete the call to ResetOrientationAndPosition below (appropriate if not supporting 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)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void ABPCommunicationCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void ABPCommunicationCharacter::MoveForward(float Value)
{
if ((Controller != nullptr) && (Value != 0.0f))
{
// find out which way is forward
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get forward vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
AddMovementInput(Direction, Value);
}
}
void ABPCommunicationCharacter::MoveRight(float Value)
{
if ( (Controller != nullptr) && (Value != 0.0f) )
{
// find out which way is right
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get right vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
// add movement in that direction
AddMovementInput(Direction, Value);
}
}
- [Play (プレイ)] を押して BP_RotateActor アクタに近づいたときのみ、それが回転するかどうか確認します。
(w:600)(convert:false)
次のステップ
ブループリント キャスティングの使い方が分かったところで、今度は「アクタ通信」ドキュメント ページで参照されている他の通信手段を見てみましょう。