Download

Manipulating Objects with C++

I’m just getting started with Unreal Engine, I’m fairly experienced in Unity, and I know C++ really well, but I’m trying to get used to UE
If I wanted to, say, change the position of a sphere when I step in to it’s collider, what would be the code to do that?

I’ve been looking up all kinds of tutorials, but the only ones I’m finding are the “Basics about C++” or “C++ Vs. Blueprint” And none of them really go over how to program anything in your scene

You could bind a function to the sphere’s OnComponentBeginOverlap delegate.
Provided you setup the correct collision too, it would interact with the character and move around.

Something like:



AMyActor::AMyActor(const FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer)
{
    // Create the sphere component.
    SphereComponent = ObjectInitializer.CreateOptionalDefaultSubobject<USphereComponent>(this, TEXT("MySphereComponent"));
    
    if (SphereComponent != nullptr)
    {
        // Give it radius of 50cm.
        SphereComponent->InitSphereRadius(50.0f);
        
        // Make it collide with pawns/characters.
        static FName CollisionProfileName(TEXT("Pawn"));
        SphereComponent->SetCollisionProfileName(CollisionProfileName);
        
        // When it does, fire off OnOverlap().
        SphereComponent->OnComponentBeginOverlap.AddDynamic(this, &AMyActor::OnOverlap);
        
        // Make this out root component.
        RootComponent = SphereComponent;
    }
}

void AMyActor::OnOverlap(AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
    if (OtherActor != nullptr)
    {    
        // Get the direction away the other actor.
        FVector Direction = GetActorLocation() - OtherActor->GetActorLocation();
        Direction = Direction.GetSafeNormal();
        
        // Set our new location 5m away from the actor.
        FVector NewLocation = GetActorLocation() + (Direction * 500.0f);
        
        // Move.
        SetActorLocation(NewLocation);
    }
}