Skip to content

Instantly share code, notes, and snippets.

@shadowmint
Created April 16, 2015 00:44
Show Gist options
  • Save shadowmint/b8a37282d4ad2d84afcf to your computer and use it in GitHub Desktop.
Save shadowmint/b8a37282d4ad2d84afcf to your computer and use it in GitHub Desktop.
#include "UtilsPluginPrivatePCH.h"
#include "Utils/Camera/Utils_CameraFollow.h"
#include "api/Actor.h"
#include "api/Camera.h"
#include "api/Player.h"
#include "api/Debug.h"
UUtils_CameraFollow::UUtils_CameraFollow() {
bWantsInitializeComponent = true;
PrimaryComponentTick.bCanEverTick = true;
}
void UUtils_CameraFollow::InitializeComponent() {
Super::InitializeComponent();
elapsed = 0.0;
if (camera) {
Debug::Trace(this, "No camera bound to UUtils_CameraFollow instance");
}
}
void UUtils_CameraFollow::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) {
Super::TickComponent( DeltaTime, TickType, ThisTickFunction );
if (camera) {
if (!player) {
player = api::Player::Local(this).Or(NULL);
if (player) {
target = api::Player::Pawn(player);
LookAtPlayer();
}
}
else {
elapsed += DeltaTime;
if (elapsed >= update_interval) {
TrackPlayer();
elapsed = 0.0;
}
}
}
}
void UUtils_CameraFollow::LookAtPlayer() {
api::Player::SetCamera(player, camera);
api::Camera::LookAt(camera, player);
}
void UUtils_CameraFollow::TrackPlayer() {
auto cloc = api::Actor::Position(camera);
auto ploc = api::Actor::Position(target);
if (follow_x) { cloc.X = ploc.X; }
if (follow_y) { cloc.Y = ploc.Y; }
if (follow_z) { cloc.Z = ploc.Z; }
api::Actor::Move(camera, cloc);
}
#pragma once
#include "Components/ActorComponent.h"
#include "Camera/CameraActor.h"
#include "Utils_CameraFollow.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class UTILSPLUGIN_API UUtils_CameraFollow : public UActorComponent
{
GENERATED_BODY()
private:
/// Elapsed time since last action
float elapsed;
/// Look at the target
void LookAtPlayer();
/// Track along with the target
void TrackPlayer();
public:
// Sets default values for this component's properties
UUtils_CameraFollow();
// Called when the game starts
virtual void InitializeComponent() override;
// Called every frame
virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
ACameraActor *camera;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
APlayerController *player;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
APawn *target;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float update_interval;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool follow_x;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool follow_y;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool follow_z;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment