First, you do want to calculate socketOffset before attaching. After attaching, “item->GetActorLocation()” will give you non-world location.
The line:
FVector socketOffset = item->GetMesh()->GetSocketLocation("AttachOrigin") - item->GetActorLocation();
would only work if the ‘item’ has no rotation to begin with. If you give it some random rotations and try it again, you’ll see it’ll be off.
You do want to find an offset from your item origin to the socket, but you need to find them in local space.
If you want to do it a quick-and-dirty way you can do:
item->SetActorRotation(FRotator(0.0f, 0.0f, 0.0f));
FVector socketOffset = item->GetMesh()->GetSocketLocation("AttachOrigin") - item->GetActorLocation();
The “AttachRootComponentTo” will overwrite the item’s rotation anyway, so zeroing it out before the socketOffset calculation is not too much of a hack.
Now, if you rotate the item, you’ll notice it will act weird and not rotate around the socket. This is because you need to rotate the item in local space. The problem is that “SetActorRelativeRotation” and “GetActorRotation” work in different coordinate spaces. “SetActorRelativeRotation” works in the new local space, child of “RightHand”, whereas “GetActorRotation” returns values in the space of “RightHand” itself. So doing a get with one and set with the other will be screwed up.
This will work:
FRotator Rot(item->GetRootComponent()->GetRelativeTransform().GetRotation());
Rot.Yaw += degree;
FVector NewOfs = Rot.RotateVector(socketOffset);
item->SetActorRelativeRotation(Rot);
item->SetActorRelativeLocation(NewOfs);
Here I’m rotating by ‘degree’ in Yaw, but it can be anything.
“socketOffset” you calculate when you attach the object, but keep it as a class variable rather than a local variable.
item->SetActorRotation(FRotator(0.0f, 0.0f, 0.0f));
socketOffset = item->GetMesh()->GetSocketLocation("AttachOrigin")
item->AttachRootComponentTo(GetMesh(), "RightHand", EAttachLocation::SnapToTarget, true);
item->SetActorRelativeLocation(MyActorOfs);
This code worked for me and tested it in UE 4,9.3