-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPlayerPickup.cs
102 lines (85 loc) · 2.96 KB
/
PlayerPickup.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FishNet.Object;
// Reference Bobi https://forum.unity.com/threads/3d-character-picking-up-item.900098/
public class PlayerPickup : NetworkBehaviour
{
[SerializeField] float raycastDistance;
[SerializeField] LayerMask pickupLayer;
[SerializeField] Transform pickupPosition;
[SerializeField] KeyCode pickupButton = KeyCode.E;
[SerializeField] KeyCode dropButton = KeyCode.Q;
Camera cam;
bool hasObjectInHand;
GameObject objInHand;
Transform worldObjectHolder;
public override void OnStartClient()
{
base.OnStartClient();
if (!base.IsOwner)
enabled = false;
cam = Camera.main;
worldObjectHolder = GameObject.FindGameObjectWithTag("WorldObjects").transform;
}
private void Update()
{
if (Input.GetKeyDown(pickupButton))
Pickup();
if (Input.GetKeyDown(dropButton))
Drop();
}
void Pickup()
{
if(Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, raycastDistance, pickupLayer))
{
if (!hasObjectInHand)
{
SetObjectInHandServer(hit.transform.gameObject, pickupPosition.position, pickupPosition.rotation, gameObject);
objInHand = hit.transform.gameObject;
hasObjectInHand = true;
}
else if(hasObjectInHand)
{
Drop();
SetObjectInHandServer(hit.transform.gameObject, pickupPosition.position, pickupPosition.rotation, gameObject);
objInHand = hit.transform.gameObject;
hasObjectInHand = true;
}
}
}
[ServerRpc(RequireOwnership = false)]
void SetObjectInHandServer(GameObject obj, Vector3 position, Quaternion rotation, GameObject player)
{
SetObjectInHandObserver(obj, position, rotation, player);
}
[ObserversRpc]
void SetObjectInHandObserver(GameObject obj, Vector3 position, Quaternion rotation, GameObject player)
{
obj.transform.position = position;
obj.transform.rotation = rotation;
obj.transform.parent = player.transform;
if (obj.GetComponent<Rigidbody>() != null)
obj.GetComponent<Rigidbody>().isKinematic = true;
}
void Drop()
{
if(!hasObjectInHand)
return;
DropObjectServer(objInHand, worldObjectHolder);
hasObjectInHand = false;
objInHand = null;
}
[ServerRpc(RequireOwnership = false)]
void DropObjectServer(GameObject obj, Transform worldHolder)
{
DropObjectObserver(obj, worldHolder);
}
[ObserversRpc]
void DropObjectObserver(GameObject obj, Transform worldHolder)
{
obj.transform.parent = worldHolder;
if(obj.GetComponent<Rigidbody>() != null)
obj.GetComponent<Rigidbody>().isKinematic = false;
}
}