【UnrealEngine】円運動をするアクタに傾きを与える!【C++】
前回は円運動をするアクタを作成してみたのですが、今回はそのアクタに傾きを与えてみようと思います。
◆前回作成したアクタがこちら
◆今回作成していく傾きを与えたアクタ
前回作成したアクタの記事とは少し異なる部分があるため、そちらは後程記載してますのでご安心ください。
ということでここからはさっそくコードに移っていこうと思います!
ヘッダーファイル
変数を作成しておく
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "RotateAngleActor.generated.h"
UCLASS()
class CREATEACTOR_API ARotateAngleActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ARotateAngleActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
FVector StartLocation;
float RunTime = 0.0f;
float Radius = 200.0f;
float Speed = 1.0f;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
ソースファイル
円運動と傾きの設定
// Fill out your copyright notice in the Description page of Project Settings.
#include "RotateAngleActor.h"
// Sets default values
ARotateAngleActor::ARotateAngleActor()
{
// 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;
}
// Called when the game starts or when spawned
void ARotateAngleActor::BeginPlay()
{
Super::BeginPlay();
StartLocation = GetActorLocation();
}
// Called every frame
void ARotateAngleActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
RunTime += DeltaTime;
FVector Offset = FVector(
FMath::Cos(RunTime * Speed),
FMath::Sin(RunTime * Speed),
0) * Radius;
Offset = Offset.RotateAngleAxis(45, FVector::RightVector);
SetActorLocation(StartLocation + Offset);
}
一部コード内容に変更を加えています。
前回記述していたコード
C++ Example
float X = FMath::Sin(RunTime * MoveSpeed) * MoveRadius;
float Y = FMath::Cos(RunTime * MoveSpeed) * MoveRadius;
調べてみたところ、まとめて記載しておく方が分かりやすいとのことが判明したので、下記コードに変更して円運動の記述をしてみました。
変数名が前回と異なるため多少分かりにくいかもしれませんが処理はこれで同じになります。
前回記述していたコード
C++ Example
FVector Offset = FVector(
FMath::Cos(RunTime * Speed),
FMath::Sin(RunTime * Speed),
0) * Radius;
ちなみに傾きを制御しているのは下記コードの部分ですね!
Offsetは前述しているFVector変数でその中にあるRotate関数を使ってます。角度と軸を設定することによって傾きを作っているコードですね。
45:角度
RightVector:軸(Y)
※RightVectorのほかにも「UpVector」というZ軸と「ForwardVector」X軸を設定する項目もあり。
コードの傾きはここ!
C++ Example
Offset = Offset.RotateAngleAxis(45, FVector::RightVector);
ということで今回はここまで!
◆YouTube
ゆうtuber・ゆうくん – YouTube
