-
Notifications
You must be signed in to change notification settings - Fork 0
/
SyncPhysics.cpp
81 lines (69 loc) · 2.31 KB
/
SyncPhysics.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "SyncPhysics.h"
#include "GameFramework/Actor.h"
#include "Components/PrimitiveComponent.h"
#include "Net/UnrealNetwork.h"
USyncPhysics::USyncPhysics()
{
PrimaryComponentTick.bCanEverTick = true;
SetIsReplicatedByDefault(true);
bEnablePhysicsReplication = true;
}
void USyncPhysics::BeginPlay()
{
Super::BeginPlay();
if (GetOwner())
{
RootComp = Cast<UPrimitiveComponent>(GetOwner()->GetRootComponent());
}
}
void USyncPhysics::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (bEnablePhysicsReplication)
{
ReplicatePhysics();
}
}
void USyncPhysics::ReplicatePhysics()
{
if (RootComp && RootComp->IsSimulatingPhysics())
{
FVector NewPosition = RootComp->GetComponentLocation();
FVector NewVelocity = RootComp->GetPhysicsLinearVelocity();
FRotator NewRotation = RootComp->GetComponentRotation();
if (GetOwner()->HasAuthority())
{
Server_SyncPhysicsState(NewPosition, NewVelocity, NewRotation);
}
else
{
ApplyPhysicsState(LastPosition, LastVelocity, LastRotation);
}
}
}
void USyncPhysics::ApplyPhysicsState(const FVector& NewPosition, const FVector& NewVelocity, const FRotator& NewRotation)
{
if (RootComp)
{
RootComp->SetWorldLocation(NewPosition);
RootComp->SetPhysicsLinearVelocity(NewVelocity);
RootComp->SetWorldRotation(NewRotation);
}
}
void USyncPhysics::Server_SyncPhysicsState_Implementation(const FVector& NewPosition, const FVector& NewVelocity, const FRotator& NewRotation)
{
LastPosition = NewPosition;
LastVelocity = NewVelocity;
LastRotation = NewRotation;
}
bool USyncPhysics::Server_SyncPhysicsState_Validate(const FVector& NewPosition, const FVector& NewVelocity, const FRotator& NewRotation)
{
return true;
}
void USyncPhysics::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(USyncPhysics, LastPosition);
DOREPLIFETIME(USyncPhysics, LastVelocity);
DOREPLIFETIME(USyncPhysics, LastRotation);
}