Add a custom sprint arm component that can smoothly avoic collisions

This commit is contained in:
Steve Streeting 2024-03-13 18:04:28 +00:00
parent ca8e56a9a4
commit 84e4560cde
2 changed files with 75 additions and 0 deletions

View File

@ -0,0 +1,41 @@

#include "StevesSpringArmComponent.h"
UStevesSpringArmComponent::UStevesSpringArmComponent()
{
}
FVector UStevesSpringArmComponent::BlendLocations(const FVector& DesiredArmLocation,
const FVector& TraceHitLocation,
bool bHitSomething,
float DeltaTime)
{
// These locations are in world space, we only want to blend the arm length, not the rest
const FVector Base = Super::BlendLocations(DesiredArmLocation, TraceHitLocation, bHitSomething, DeltaTime);
if (bEnableSmoothCollisionAvoidance)
{
// Convert these back to arm lengths
// PreviousArmOrigin has been already set and is the world space origin
const float TargetArmLen = (Base - PreviousArmOrigin).Length();
const float NewArmLen = FMath::FInterpTo(PrevArmLength.Get(TargetArmLen), TargetArmLen, DeltaTime, SmoothCollisionAvoidanceSpeed);
// Perform the same transformation again using the new arm length
// Now offset camera position back along our rotation
FVector Ret = PreviousDesiredLoc - PreviousDesiredRot.Vector() * NewArmLen;
// Add socket offset in local space
Ret += FRotationMatrix(PreviousDesiredRot).TransformVector(SocketOffset);
PrevArmLength = NewArmLen;
return Ret;
}
else
{
return Base;
}
}

View File

@ -0,0 +1,34 @@

#pragma once
#include "CoreMinimal.h"
#include "GameFramework/SpringArmComponent.h"
#include "StevesSpringArmComponent.generated.h"
UCLASS(ClassGroup=(Custom), meta=(BlueprintSpawnableComponent))
class STEVESUEHELPERS_API UStevesSpringArmComponent : public USpringArmComponent
{
GENERATED_BODY()
public:
/// Whether to move the camera smoothly to avoid collisions rather than jumping instantly
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=CameraCollision)
uint32 bEnableSmoothCollisionAvoidance : 1 = true;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=CameraCollision)
float SmoothCollisionAvoidanceSpeed = 5;
protected:
TOptional<float> PrevArmLength;
public:
UStevesSpringArmComponent();
protected:
virtual FVector BlendLocations(const FVector& DesiredArmLocation,
const FVector& TraceHitLocation,
bool bHitSomething,
float DeltaTime) override;
};