That’s right. Ideally, I want the gun’s muzzle to align with the target, or at least face in a similar direction, otherwise the bullets will shoot out at an angle completely inconsistent with the muzzle. However, I’m not sure what the exact solution is for this problem.
While looking for solutions, I found that some people adjusted the skeleton to achieve good results. However, the X-axis of my skeleton is not aligned with the arm direction, which means I might need to apply some geometric transformations to achieve a similar effect.
The original code is as follows:
FTransform RightHandTransform = PlayerCharacter->GetMesh()
->GetSocketTransform(FName(TEXT("右手首")), RTS_World);
RightHandRotation = UKismetMathLibrary::FindLookAtRotation(RightHandTransform.GetLocation(),
PlayerCharacter->GetHitTarget() ) + FRotator(135.f, 0.f, 0.f);
FTransform MuzzleTipTransform =
EquippedWeapon -> GetWeaponMesh()->GetSocketTransform(FName("MuzzleFlash"), RTS_World);
FVector MuzzleX(FRotationMatrix(MuzzleTipTransform.GetRotation().Rotator()).GetUnitAxis(EAxis::X));
FVector PlayerX(FRotationMatrix(RightHandTransform.GetRotation().Rotator()).GetUnitAxis(EAxis::X));
FVector PlayerY(FRotationMatrix(RightHandTransform.GetRotation().Rotator()).GetUnitAxis(EAxis::Y));
FVector PlayerZ(FRotationMatrix(RightHandTransform.GetRotation().Rotator()).GetUnitAxis(EAxis::Z));
DrawDebugLine(GetWorld(),
RightHandTransform.GetLocation(), PlayerCharacter->GetHitTarget(), FColor::Yellow);
DrawDebugLine(GetWorld(),
RightHandTransform.GetLocation(), RightHandTransform.GetLocation()+1000.f*PlayerX, FColor::Red);
DrawDebugLine(GetWorld(),
RightHandTransform.GetLocation(), RightHandTransform.GetLocation()+1000.f*PlayerY, FColor::Green);
DrawDebugLine(GetWorld(),
RightHandTransform.GetLocation(), RightHandTransform.GetLocation()+1000.f*PlayerZ, FColor::Blue);
DrawDebugLine(GetWorld(),
RightHandTransform.GetLocation(), RightHandTransform.GetLocation()-1000.f*PlayerZ-1000.f*PlayerX, FColor::White);
DrawDebugLine(GetWorld(),
MuzzleTipTransform.GetLocation(), MuzzleTipTransform.GetLocation()+1000.f*MuzzleX, FColor::Black);
And the result:
The white line represents the direction of the palm, while the black line represents the direction of the muzzle.
Then I directly adjusted the rotation. Although the palm is facing the correct direction, it is quite obvious that the other directions are a bit off.
RightHandRotation = UKismetMathLibrary::FindLookAtRotation(RightHandTransform.GetLocation(),
PlayerCharacter->GetHitTarget() ) + FRotator(135.f, 0.f, 0.f);
I think this might involve some geometric transformations, but I’m not sure how to do it.