Search code examples
c++unreal-engine4

(UE4) How can i set the position of bones using c++ only


i just want to know if there is a way to set bones of a skeletal mesh to a specific position in c++. I do not want to use blueprints and i did not find a good way of doing it.


Solution

  • Look up the UPoseableMeshComponent. It allows you to set the transform for each of a skeleton's bones.

    edit:

    Here's an example of how I use a PoseableMeshComponent in a project. In my case I'm replicating a skeleton that's being driven by mocap data. The mocap data is received from a networking socket and stored into a struct that looks like this:

    USTRUCT()
    struct FSkeletonData
    {
    GENERATED_USTRUCT_BODY()
    
    FSkeletonData()
        : Scale(1.0f)
    {}
    /**
     * The bones' location
     */
    UPROPERTY(VisibleAnywhere)
    TArray<FVector> Locations;
    /**
     *  The bones' rotation
     */
    UPROPERTY(VisibleAnywhere)
    TArray<FQuat> Rotations;
    /**
     *  Scale of the skeletal mesh
     */
    UPROPERTY(VisibleAnywhere)
    float Scale;
    }
    

    The class that's receiving this data has a PoseableMeshComponent and updates it based on this struct like this:

    int32 NumBones = PoseableMeshComponent->GetNumBones();
    
    for (int32 i = 0; i < NumBones; ++i)
        {
            FName const BoneName = PoseableMeshComponent->GetBoneName(i);
    
            FTransform Transform(SkeletonDataActual.Rotations[i], SkeletonDataActual.Locations[i], FVector(SkeletonDataActual.Scale));
    
            PoseableMeshComponent->SetBoneTransformByName(BoneName, Transform, EBoneSpaces::WorldSpace);
        }
        PoseableMeshComponent->SetWorldScale3D(FVector(SkeletonDataActual.Scale));
    

    Note that SkeletonDataActual is of the FSkeletonData type, and these positions are in World Space. You might need to add your actor's location and/or rotation if you want it to work in local space.

    Hope that helps you, good luck!