Hi,
I am trying to implement a ADS (Aim down sights) for my FPS game, and I am having some issues with AttachToComponent.
I have a FPS Arms Mesh which is a child of my Camera.
To implement ADS, I detach the arms mesh, move the camera to the aimpoint socket location (on my weapon), then reattach the arms mesh to the camera.
I have set the attachment rule to KeepWorld, but it does not seem to respect this, and instead I get some strange rotation on my arms mesh after attaching it back.
// Get player camera (Arms mesh is child of camera)
UCameraComponent* PlayerCamera = Player->GetCamera();
// Get aimpoint transform (in world space)
const FTransform AimPointTransform { Player->GetEquippedWeapon()->GetAimpointTransform() };
// Calculate aimpoint relative transform to camera's parent transform
const FTransform CameraParentTransform { PlayerCamera->GetAttachParent()->GetComponentTransform() };
const FTransform Transform { UKismetMathLibrary::MakeRelativeTransform(AimPointTransform, CameraParentTransform) };
// Temporarily detach mesh from camera (otherwise mesh will move with camera as well)
const FDetachmentTransformRules DetachmentTransformRules { EDetachmentRule::KeepWorld, true };
Player->GetArmsMesh()->DetachFromComponent(DetachmentTransformRules);
// Set camera relative transform to the aimpoint
PlayerCamera->SetRelativeTransform(Transform);
// Set mesh back to camera as parent after moved (Does not work as expected)
const FAttachmentTransformRules AttachmentTransformRules { EAttachmentRule::KeepWorld, EAttachmentRule::KeepWorld, EAttachmentRule::KeepWorld, false };
Player->GetArmsMesh()->AttachToComponent(PlayerCamera, AttachmentTransformRules);
type or paste code here
If I comment out the last 2 lines and check, the Arms mesh is in the correct position and rotation in its detached state.
Why is the transform not being maintained if I reattach the mesh back to the camera?