ビデオゲームではしばしば、プレイヤーは自分のキャラクタ新しいアイテムや武器を手に入れることでエンゲージメントを維持し、時には新しい敵が現れて敗北することもあります。
ゲームの中に、ゲームプレイ中にレベルにアイテムや敵を動的に追加したいと感じる場合があります。これをスポーンといいます。
この操作ガイドでは、ボタンを押した時にアクタ スポナーからスポーンされる Actor クラスを作成します。また、別のボタンを押すとスポーンされたアクタを破壊するロジックを作成します。

スポーンするアクタを作成する
このセクションでは、球体コンポーネント、スタティックメッシュ コンポーネント、パーティクル システム コンポーネントを含むアクタを作成します。
-
スターター コンテンツ を有効にした Third Person Blueprint ゲーム プロジェクトを新規作成します。新しく作成したプロジェクトに SpawnDestroy と名前を付けます。
-
コンテンツ ブラウザ から [Add/Import (追加 / インポート)] ボタンを選択して Bp_ActorToSpawn という名前の Blueprint アクタ を新規作成します。
-
Class Defaults で [Components] タブを開き [Add Component] を選択します。Sphere Component を探して選択し、Scene Component へドラッグして新しい Root Component とします。
-
Sphere Component の [Details] パネルの Shape で Sphere Radius の値を 16.0 にします。
-
Physics カテゴリで Simulate Physics 変数の横のボックスにチェックを入れます。
-
[Components] タブで Add Component を選択し Static Mesh Component を探して選択します。
-
[Details] パネルから Static Mesh カテゴリに移動し、 Static Mesh 変数の横にあるドロップダウン矢印を選択し、Shape_Sphere Static Mesh アセットを探して選択します。
-
Transform カテゴリの Scale 変数の X、Y、Z の値をそれぞれ 0.25、0.25、0.25 に変更します。Location 変数で Z 値を -12.0 に変更します。
-
[Components] タブを開き [Add Component] を選択します。Particle System Component を選択します。
- [Details] パネルから Particles カテゴリに移動し、Template 変数の横にあるドロップダウン矢印を選択して P_Fire を検索して選択します。
-
ブループリント を コンパイル して 保存 します。
完成したブループリント

アクタ スポナーを作成する
スポーンするアクタを作成したので、新しい Bp_ActorSpawn アクタをスポーンするためのカスタム機能を使用するアクタ スポナーを作成します。
-
コンテンツ ブラウザ から [Add/Import (追加 / インポート)] ボタンを選択して Bp_ActorToSpawn という名前の Blueprint アクタ を新規作成します。
-
Class Defaults で [Components] タブを開き [Add Component] を選択します。Box Component アセットを探して選択し SpawnVolume と名前を付けます。
-
イベントグラフ を右クリックして、Actions コンテキスト メニューから Add Custom Event を選択して SpawnActor と名前を付けます。
-
Spawn Actor Custom Event 実行ピンを引き出して Executable actions ドロップダウン メニューから Spawn Actor From Class を選択します。
-
SpawnActor ノードの Class ピンから BP_ActorToSpawn クラスを選択します。
-
Spawn Actor from Class ノードから Spawn Transform ピンを引き出して Actions ドロップダウン メニューから Get Actor Transform を選択します。
-
ブループリントを コンパイル して 保存 します。
完成したブループリント

追加のキャラクター アクション コマンドを設定する
Bp_ActorToSpawn と Bp_ActorSpawner の 2 つのアクタ クラスを作成すると、アクタ スポナーのスポーン アクタ関数を呼び出す機能を備えたサードパーソン キャラクターを設定します。
-
[Edit] > [Project Settings] > [Engine] > [Input] に移動してから、Bindings カテゴリで Action Mappings カテゴリの隣にある [+] マークをクリックし、SpawnActors と DestroyActors という名前の 2 つのマッピングを追加します。
- SpawnActors アクション キー マッピングを 1 キーに、 DestroyActors アクション キー マッピングを 2 キーに設定します。
-
コンテンツ ブラウザ から Third Person Character ブループリントを開いてクラス デフォルトをダブルクリックして イベントグラフ を右クリックします。All Actions for this Blueprint コンテキスト メニューで SpawnActors 入力アクションを探して選択します。
-
Pressed 実行ピンを引き出して Executable actions ドロップダウン メニューから Get Actor Of Class ノードを選択します。Actor Class のドロップダウン矢印をクリックして Bp Actor Spawner を選択します。
-
Get Actor of Class ノードの Return value pin を引き出します。アクション メニュー 検索で呼び出し関数 Spawn Actor を選択し、Get Actor Of Class ノードから実行ピンを Spawn Actor ノードに接続します。
-
イベントグラフ を右クリックして、コンテキスト メニューから DestroyActors 入力アクションイベントを選択します。
-
Pressed 実行ピンを引き出して Executable actions ドロップダウン メニューから Get Actor Of Class ノードを選択します。Actor Class のドロップダウン矢印をクリックして Bp Actor to Spawn を選択します。
-
Out Actors Return 値ピン実行ピンを引き出してドロップダウン メニューから For Each Loop With Break ノードを選択します。
-
Array Element ピンを引き出して アクション メニュー検索で Destroy Actor 関数を選択し、Get All Actors of Class ノードから実行ピンを For Each Loop with Break ノードの 実行ピン に接続します。
-
For Each Loop with Break ノードから Loop Body 実行ピンを引き出して Destroy Actor 入力実行ピンに接続します。
-
コンパイル して 保存 します。
完成したブループリント

シーンの設定
プレイヤー キャラクターが Bp_Spawner の SpawnActor 関数を呼び出すために必要な機能の作成が完了したので、レベルに Bp_Spawner の場所を選択する必要があります。
-
コンテンツ ブラウザ から Bp_ActorSpawner のインスタンスをレベルにドラッグします。
-
Bp_ActorSpawner をテストするための PIE (Play-In Editor) を選択します。
最終結果
エディタでテストするときに 1 キーを押すと Actor Spawner クラスがレベルにスポーンするためのアクタをスポーンします。2 キーを押すと、レベル内のすべての ActorsToSpawn が破棄されます。
[]!(image_33.gif)(convert:false)
スポーンするアクタを作成する
-
スターター コンテンツ を有効にした Third Person C++ games project を新規作成します。新しく作成したプロジェクトに SpawnDestroy と名前を付けます。
-
C++ Class ウィザード で ActorToSpawn という名前の Actor クラスを新規作成します。
-
ActorToSpawn.h のクラス デフォルトで以下のコードを実行します。
protected: UPROPERTY(EditAnywhere, BlueprintReadWrite) class USphereComponent* SphereComp; UPROPERTY(EditAnywhere, BlueprintReadWrite) UStaticMeshComponent* StaticMeshComp; UPROPERTY(EditAnywhere, BlueprintReadWrite) class UParticleSystemComponent* ParticleComp;
-
ActorToSpawn.cpp ファイルに移動して以下のクラス メソッドを宣言します。
#include "Components/SphereComponent.h" #include "Particles/ParticleSystemComponent.h"
-
AActorToSpawn::AActorToSpawn コンストラクタで以下のコードを実行します。
AActorToSpawn::AActorToSpawn() { // 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; //Creating our Default Components SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere")); StaticMeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp")); ParticleComp = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ParticleComp")); //Attaching the Components and setting physics SphereComp->SetupAttachment(RootComponent); SphereComp->SetSimulatePhysics(true); SphereComp->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); StaticMeshComp->AttachToComponent(SphereComp,FAttachmentTransformRules::KeepRelativeTransform); ParticleComp->AttachToComponent(StaticMeshComp,FAttachmentTransformRules::KeepRelativeTransform); //Setting the Sphere radius to be of a smaller size in line with the Static Mesh. SphereComp->SetSphereRadius(16.0f); //Setting the Static Mesh Scale and Location to fit the radius of the Sphere. StaticMeshComp->SetRelativeLocation(FVector(0.0, 0.0, -12.0f)); StaticMeshComp->SetRelativeScale3D(FVector(0.25, 0.25, 0.25)); //Using Constructor Helpers to set our Static Mesh Comp with a Sphere Shape. static ConstructorHelpers::FObjectFinder<UStaticMesh>SphereMeshAsset(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere'")); StaticMeshComp->SetStaticMesh(SphereMeshAsset.Object); //Using Constructor Helpers to set our Particle Comp with our Fire Particle Comp. static ConstructorHelpers::FObjectFinder<UParticleSystem>ParticleCompAsset(TEXT("ParticleSystem'/Game/StarterContent/Particles/P_Fire.P_Fire'")); ParticleComp->SetTemplate(ParticleCompAsset.Object); }
-
コードを コンパイル します。
-
エディタで C++ クラス フォルダ へ移動し、ActorToSpawn を右クリックします。コンテキスト メニューから Create Blueprint class based on ActorToSpawn を選択します。
完成された Bp_ActorToSpawn は以下の画像のようになります。
完成コード
ActorToSpawn.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ActorToSpawn.generated.h"
UCLASS()
class SPAWNDESTROYCPP_API AActorToSpawn : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AActorToSpawn();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
class USphereComponent* SphereComp;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UStaticMeshComponent* StaticMeshComp;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
class UParticleSystemComponent* ParticleComp;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
ActorToSpawn.cpp
#include "ActorToSpawn.h"
#include "Components/SphereComponent.h"
#include "Particles/ParticleSystemComponent.h"
// Sets default values
AActorToSpawn::AActorToSpawn()
{
// 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;
//Creating our Default Components
SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere"));
StaticMeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp"));
ParticleComp = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ParticleComp"));
//Attaching the Components and setting physics
SphereComp->SetupAttachment(RootComponent);
SphereComp->SetSimulatePhysics(true);
SphereComp->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
StaticMeshComp->AttachToComponent(SphereComp,FAttachmentTransformRules::KeepRelativeTransform);
ParticleComp->AttachToComponent(StaticMeshComp,FAttachmentTransformRules::KeepRelativeTransform);
//Setting the Sphere radius to be of a smaller size in line with the Static Mesh.
SphereComp->SetSphereRadius(16.0f);
//Setting the Static Mesh Scale and Location to fit the radius of the Sphere.
StaticMeshComp->SetRelativeLocation(FVector(0.0, 0.0, -12.0f));
StaticMeshComp->SetRelativeScale3D(FVector(0.25, 0.25, 0.25));
}
// Called when the game starts or when spawned
void AActorToSpawn::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AActorToSpawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
アクタ スポナーを作成する
スポーンするアクタを作成したので、新しいアクタをスポーンするカスタム機能を使用するアクタ スポナーを作成します。
-
C++ Class ウィザード で ActorSpawner という名前の Actor クラスを新規作成します。
-
ActorSpawner.h のクラス デフォルトで以下のコードを実行します。
public: UFUNCTION() void SpawnActor(); protected: UPROPERTY(EditAnywhere,BlueprintReadWrite) class UBoxComponent* SpawnVolume;
-
ActorSpawner.cpp へ移動し以下のライブラリをインクルードします。
#include "Components/BoxComponent.h" #include "ActorToSpawn.h"
-
AActorSpawner::AActorSpawner コンストラクタで以下のコードを実行します。
AActorSpawner::AActorSpawner() { RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("DefaultSceneRoot")); SpawnVolume = CreateDefaultSubobject<UBoxComponent>(TEXT("SpawnVolume")); SpawnVolume->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform); }
-
Implement the following code for the AActorSpawner::SpawnActor class method.
void AActorSpawner::SpawnActor() { FVector SpawnLocation = GetActorLocation(); FRotator SpawnRotation = GetActorRotation(); GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation); }
-
コードを コンパイル します。
-
コンテンツ ブラウザ から「C++ classes フォルダ」に移動し、ActorSpawner クラスを右クリックして、[C++ Class Actions] コンテキスト メニューから Bp_ActorSpawner という名前の Create Blueprint class based on ActorSpawner を選択します。
完成したブループリントは、次の画像のようになります。
Finished Code
ActorSpawner.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ActorSpawner.generated.h"
UCLASS()
class SPAWNDESTROYCPP_API AActorSpawner : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AActorSpawner();
UFUNCTION()
void SpawnActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY(EditAnywhere,BlueprintReadWrite)
class UBoxComponent* SpawnVolume;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
ActorSpawner.cpp
#include "ActorSpawner.h"
#include "Components/BoxComponent.h"
#include "ActorToSpawn.h"
// Sets default values
AActorSpawner::AActorSpawner()
{
// 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("DefaultSceneRoot"));
SpawnVolume = CreateDefaultSubobject<UBoxComponent>(TEXT("SpawnVolume"));
SpawnVolume->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
}
// Called when the game starts or when spawned
void AActorSpawner::BeginPlay()
{
Super::BeginPlay();
}
void AActorSpawner::SpawnActor()
{
FVector SpawnLocation = GetActorLocation();
FRotator SpawnRotation = GetActorRotation();
GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation);
}
// Called every frame
void AActorSpawner::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
追加のキャラクター アクション コマンドを設定する
アクタ クラスとアクタ スポナー クラスの両方を設定したら、アクタ スポナーのスポーン アクタ関数を呼び出す機能を備えたサードパーソン キャラクターを設定します。また、プレイヤーにアクタ スポナーのスポーン アクタ関数を呼び出す機能を提供するために、プレイヤー キャラクターの入力キーマッピングをマッピングする必要があります。
-
[Edit] > [Project Settings] > [ Input] に移動してから、Bindings カテゴリで Action Mappings の隣にある [+] マークをクリックし、SpawnActors and DestroyActors という名前の アクション マッピング を追加します。
-
SpawnActors アクション キー マッピングを 1 キーに、 DestroyActors アクション キー マッピングを 2 キーに設定します。
-
ThirdPersonCharacter.h ファイルを開き、以下のクラスを宣言します。
protected: void SpawnActors(); void DestroyActors();
-
ThirdPersonCharacter.cpp へ移動し以下のライブラリをインクルードします。
#include "Kismet/GameplayStatics.h" #include "ActorSpawner.h" #include "ActorToSpawn.h"
GameplayStatics には、Blueprint と C ++ の両方から呼び出すことができる便利なゲームプレイ ユーティリティ関数が含まれています。詳細は、API ドキュメントの「GameplayStatics」を参照してください。
-
ASpawnDestroyCppCharacter::SpawnActors メソッドと ASpawnDestroyCppCharacter::DestroyActors メソッドに次のクラス定義を実装します。
void ASpawnDestroyCppCharacter::SpawnActors() { //Find the Actor Spawner in the world, and invoke it's Spawn Actor function AActor* ActorSpawnerTofind = UGameplayStatics::GetActorOfClass(GetWorld(),AActorSpawner::StaticClass()); AActorSpawner* ActorSpawnerReference = Cast<AActorSpawner>(ActorSpawnerTofind); if (ActorSpawnerReference) { ActorSpawnerReference->SpawnActor(); } } void ASpawnDestroyCppCharacter::DestroyActors() { //Get every Actor to Spawn in the world and invoke Destroy Actor TArray<AActor*> FoundActors; UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActorToSpawn::StaticClass(), FoundActors); for (AActor* ActorFound :FoundActors) { ActorFound->Destroy(); } }
-
ASpawnDestroyCppCharacter::SetupPlayerInputComponent に移動し、次のコードを追加します。
void ASpawnDestroyCppCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { PlayerInputComponent->BindAction("SpawnActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::SpawnActors); PlayerInputComponent->BindAction("DestroyActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::DestroyActors); }
完成コード
SpawnDestroyCppCharacter.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "SpawnDestroyCppCharacter.generated.h"
UCLASS(config=Game)
class ASpawnDestroyCppCharacter : 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:
ASpawnDestroyCppCharacter();
/** 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:
/*Calls Actor Spawner in Level to Spawn their Actor to Spawn*/
void SpawnActors();
/*Gets all ActorToSpawn Actors and call their Destroy function */
void DestroyActors();
/** 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; }
};
SpawnDestroyCppCharacter.cpp
#include "SpawnDestroyCppCharacter.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 "Kismet/GameplayStatics.h"
#include "ActorSpawner.h"
#include "ActorToSpawn.h"
//////////////////////////////////////////////////////////////////////////
// ASpawnDestroyCppCharacter
ASpawnDestroyCppCharacter::ASpawnDestroyCppCharacter()
{
// 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
// 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 ASpawnDestroyCppCharacter::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("SpawnActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::SpawnActors);
PlayerInputComponent->BindAction("DestroyActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::DestroyActors);
PlayerInputComponent->BindAxis("MoveForward", this, &ASpawnDestroyCppCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &ASpawnDestroyCppCharacter::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, &ASpawnDestroyCppCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &ASpawnDestroyCppCharacter::LookUpAtRate);
// handle touch devices
PlayerInputComponent->BindTouch(IE_Pressed, this, &ASpawnDestroyCppCharacter::TouchStarted);
PlayerInputComponent->BindTouch(IE_Released, this, &ASpawnDestroyCppCharacter::TouchStopped);
// VR headset functionality
PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ASpawnDestroyCppCharacter::OnResetVR);
}
void ASpawnDestroyCppCharacter::SpawnActors()
{
//Find the Actor Spawner in the Level, and invoke it's Spawn Actor function
AActor* ActorSpawnerTofind = UGameplayStatics::GetActorOfClass(GetWorld(),AActorSpawner::StaticClass());
AActorSpawner* ActorSpawnerReference = Cast<AActorSpawner>(ActorSpawnerTofind);
if (ActorSpawnerReference)
{
ActorSpawnerReference->SpawnActor();
}
}
void ASpawnDestroyCppCharacter::DestroyActors()
{
TArray<AActor*> FoundActors;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActorToSpawn::StaticClass(), FoundActors);
for (AActor* ActorFound :FoundActors)
{
ActorFound->Destroy();
}
}
void ASpawnDestroyCppCharacter::OnResetVR()
{
// If SpawnDestroyCpp is added to a project via 'Add Feature' in the Unreal Editor the dependency on HeadMountedDisplay in SpawnDestroyCpp.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 ASpawnDestroyCppCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
Jump();
}
void ASpawnDestroyCppCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
StopJumping();
}
void ASpawnDestroyCppCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void ASpawnDestroyCppCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void ASpawnDestroyCppCharacter::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 ASpawnDestroyCppCharacter::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);
}
}
シーンの設定
プレイヤー キャラクターが Bp_Spawner の SpawnActor 関数を呼び出すために必要な機能の作成が完了したので、レベルに Bp_Spawner の場所を設定する必要があります。
1.コンテンツ ブラウザ から Bp_ Spawner のインスタンスをレベルにドラッグします。

1.PIE (Play-In Editor) を選択してスポナーをテストします。
最終結果
エディタでテストするときに 1 キーを押すと Actor Spawner クラスがレベルにスポーンするためのアクタをスポーンします。2 キーを押すと、レベル内のすべての ActorsToSpawn が破棄されます。
