Hello guys,
I changed the top-down-code sample and made it so that my character always turns to the mouse pointer.
The problem I have is with networking.
When I play in editor with 2 players, I can turn my character but others (including the server) don’t see the client rotate.
How can I replicate the rotation of each character safely and performant?
Here’s my code:
.cpp file
void ARPGTestCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (Controller && Controller->IsLocalController())
{
TurnToMouse();
}
}
void ARPGTestCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ARPGTestCharacter, targetRotation);
DOREPLIFETIME(ARPGTestCharacter, currentFacing);
}
void ARPGTestCharacter::TurnToMouse()
{
FHitResult mouseHitLocation = FHitResult();
bool bMouseHitResult = GetWorld()->GetFirstPlayerController()->GetHitResultUnderCursor(ECC_Visibility, true, mouseHitLocation);
currentChar = this;
if (bMouseHitResult)
{
FVector_NetQuantize MouseHitLocNet = FVector_NetQuantize();
MouseHitLocNet = mouseHitLocation.ImpactPoint;
FVector characterLocation = currentChar->GetActorLocation();
FVector targetVector = (MouseHitLocNet - characterLocation);
targetVector.Normalize();
targetRotation = FRotator(0.f, targetVector.Rotation().Yaw, 0.f);
}
currentChar->SetActorRotation(targetRotation);
currentFacing = targetRotation.Vector();
}
.h file
#include "GameFramework/Character.h"
#include "RPGTestCharacter.generated.h"
UCLASS(Blueprintable)
class ARPGTestCharacter : public ACharacter
{
GENERATED_BODY()
protected:
virtual void SetupPlayerInputComponent(UInputComponent* InputComponent) override;
virtual void MoveUp(float val);
virtual void MoveRight(float val);
class UCameraComponent* CameraComponent;
class USpringArmComponent* CameraSpringArm;
virtual void Tick(float DeltaTime) override;
public:
ARPGTestCharacter(const FObjectInitializer& ObjectInitializer);
void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const;
void TurnToMouse();
UPROPERTY(Replicated)
FRotator targetRotation;
UPROPERTY(Replicated)
FVector currentFacing;
ACharacter *currentChar;
inline class UCameraComponent* GetCameraComponent() const { return CameraComponent; }
inline class USpringArmComponent* GetCameraSpringArm() const { return CameraSpringArm; }
};
UnrealNetwork.h is included in the game’s main file.
Bonus question: is it even good to have a function this big in the tick function and replicate it every tick?
Thanks for your time and help
Edited main post for latest update