Here is my C++ implementation of Kris his blueprint example (WIP, need some tweaking)
In my project, the Camera is attached to a socket on the “Head” bone of the character skeleton.
Tried my code with the SurvivalGame project, but for some reasson the ADS view is located right of the weapon.
In the character class, override the CalcCamera method:
/** Calculate camera view point, when viewing this actor */
virtual void CalcCamera(float DeltaTime, struct FMinimalViewInfo& OutResult) override;
In the source file:
void ASwatCharacter::CalcCamera(float DeltaTime, struct FMinimalViewInfo& OutResult)
{
UCameraComponent* FirstPersonCamera = FindComponentByClass<UCameraComponent>();
if (FirstPersonCamera && FirstPersonCamera->IsActive())
{
FirstPersonCamera->GetCameraView(DeltaTime, OutResult);
if (bIsTargeting)
{
// Get the camera location
FVector CameraLocation = FirstPersonCamera->GetComponentLocation();
// Get the weapon sight transform
FTransform SightTransform = CurrentWeapon->GetMesh()->GetSocketTransform(FName(TEXT("SightView")));
FVector SightLocation = SightTransform.GetLocation();
FRotator SightRotation = SightTransform.GetRotation().Rotator();
// Get the sight location
FVector SightDirection = FRotationMatrix(SightRotation).GetScaledAxis(EAxis::X);
FVector DirectionToSight = SightLocation - CameraLocation;
float DirectionToSightDot = FVector::DotProduct(DirectionToSight.GetSafeNormal(), SightDirection);
float DirectionToSightLen = DirectionToSight.Size();
float DirectionToSightDotLen = DirectionToSightDot * DirectionToSightLen;
FVector SightDirectionDotLen = SightDirection * DirectionToSightDotLen;
FVector SightTargetLocation = SightLocation - SightDirectionDotLen;
float AimAlpha = IsTargeting() ? 1.0f : 0.0f;
OutResult.Location = CameraLocation + AimAlpha * (SightTargetLocation - CameraLocation);
}
}
else
{
GetActorEyesViewPoint(OutResult.Location, OutResult.Rotation);
}
}
ps: The code also work when override the “UpdateViewTarget” method in the PlayerCameraManager, so not sure what is best place to put it.