Skip to content

Instantly share code, notes, and snippets.

@mossyblog
Created December 21, 2022 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mossyblog/d0194e697c127052105ee9a21fb7f98b to your computer and use it in GitHub Desktop.
Save mossyblog/d0194e697c127052105ee9a21fb7f98b to your computer and use it in GitHub Desktop.
Unreal C++ Rope Swing Component
#include "SwingComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/SceneComponent.h"
USwingComponent::USwingComponent()
{
PrimaryComponentTick.bCanEverTick = true;
SwingForce = 1000.0f;
RopeLength = 100.0f;
ReleaseForce = 1000.0f;
bIsSwinging = false;
bIsReleasing = false;
}
void USwingComponent::BeginPlay()
{
Super::BeginPlay();
// Get a reference to the character's movement, capsule, and spring arm components
MovementComponent = GetOwner()->FindComponentByClass<UCharacterMovementComponent>();
CapsuleComponent = GetOwner()->FindComponentByClass<UCapsuleComponent>();
SpringArmComponent = GetOwner()->FindComponentByClass<USpringArmComponent>();
// Get the character's initial location
InitialLocation = GetOwner()->GetActorLocation();
}
void USwingComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// Check if the character is swinging or releasing
if (bIsSwinging || bIsReleasing)
{
FVector SwingVector;
// Calculate swing or release force based on current location and rope length
FVector Location = GetOwner()->GetActorLocation();
float Distance = FVector::Distance(Location, InitialLocation);
if (Distance > RopeLength)
{
if (bIsSwinging)
{
SwingVector = (InitialLocation - Location).GetSafeNormal() * SwingForce;
}
else if (bIsReleasing)
{
SwingVector = (Location - InitialLocation).GetSafeNormal() * ReleaseForce;
}
}
// Apply swing or release force to the character
MovementComponent->AddForce(SwingVector);
}
}
void USwingComponent::Swing()
{
bIsSwinging = true;
bIsReleasing = false;
}
void USwingComponent::Release()
{
bIsSwinging = false;
bIsReleasing = true;
}
void USwingComponent::StopSwinging()
{
bIsSwinging = false;
bIsReleasing = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment