/
ServerPlayerMove.cs
71 lines (60 loc) · 2.43 KB
/
ServerPlayerMove.cs
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
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
/// <summary>
/// Server side script to do some movements that can only be done server side with Netcode. In charge of spawning (which happens server side in Netcode)
/// and picking up objects
/// </summary>
[DefaultExecutionOrder(0)] // before client component
public class ServerPlayerMove : NetworkBehaviour
{
private ClientPlayerMove m_Client;
[SerializeField]
private Camera m_Camera;
public NetworkVariable<bool> ObjPickedUp = new NetworkVariable<bool>();
private void Awake()
{
m_Client = GetComponent<ClientPlayerMove>();
}
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (!IsServer)
{
enabled = false;
return;
}
// the following two lines should work, yet they don't. The second client connecting won't receive this position set and will spawn at the wrong position
var spawnPoint = ServerPlayerSpawnPoints.Instance.ConsumeNextSpawnPoint();
m_Client.SetSpawnClientRpc(spawnPoint.transform.position, new ClientRpcParams() { Send = new ClientRpcSendParams() { TargetClientIds = new []{OwnerClientId}}});
}
private NetworkObject m_PickedUpObj;
// DOC START HERE
[ServerRpc]
public void PickupObjServerRpc(ulong objToPickupID)
{
NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(objToPickupID, out var objToPickup);
if (objToPickup == null || objToPickup.transform.parent != null) return; // object already picked up, server authority says no
objToPickup.GetComponent<Rigidbody>().isKinematic = true;
objToPickup.transform.parent = transform;
objToPickup.GetComponent<NetworkTransform>().InLocalSpace = true;
objToPickup.transform.localPosition = Vector3.up;
ObjPickedUp.Value = true;
m_PickedUpObj = objToPickup;
}
[ServerRpc]
public void DropObjServerRpc()
{
if (m_PickedUpObj != null)
{
// can be null if enter drop zone while carying
m_PickedUpObj.transform.localPosition = new Vector3(0, 0, 2);
m_PickedUpObj.transform.parent = null;
m_PickedUpObj.GetComponent<Rigidbody>().isKinematic = false;
m_PickedUpObj.GetComponent<NetworkTransform>().InLocalSpace = false;
m_PickedUpObj = null;
}
ObjPickedUp.Value = false;
}
// DOC END HERE
}