-
Notifications
You must be signed in to change notification settings - Fork 14
/
Player.gd
494 lines (404 loc) · 16.3 KB
/
Player.gd
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
extends CharacterBody3D
signal health_changed(health_value)
signal ammo_changed(spare_ammo)
signal ammo_Changed(current_ammo)
# Set enumuration values reflect player's current camera view state
enum DynamicCameraViewToggleAction {
FIRST_PERSON_VIEW,
THIRD_PERSON_VIEW
}
# First Player View (FPP)
@onready var fpp_camera: Camera3D = $FPPCamera
@onready var fpp_raycast: RayCast3D = $FPPCamera/FPPRayCast3D
@onready var fpp_pistol: Node3D = $FPPCamera/FPPPistol
@onready var fpp_ak47: Node3D = $FPPCamera/FPPAK47
@onready var fpp_knife: Node3D = $FPPCamera/FPPKnife
@onready var fpp_pistol_muzzle_flash: GPUParticles3D = $FPPCamera/FPPPistol/MuzzleFlash
@onready var fpp_ak47_muzzle_flash: GPUParticles3D = $FPPCamera/FPPAK47/MuzzleFlash
# Third Player View (TPP)
@onready var tpp_camera: Camera3D = $TPPCamera
@onready var tpp_raycast: RayCast3D = $TPPCamera/TPPRayCast3D
@onready var tpp_pistol: Node3D = $TPPCamera/TPPPistol
@onready var tpp_ak47: Node3D = $TPPCamera/TPPAK47
@onready var tpp_knife: Node3D = $TPPCamera/TPPKnife
@onready var tpp_pistol_muzzle_flash: GPUParticles3D = $TPPCamera/TPPPistol/MuzzleFlash
@onready var tpp_ak47_muzzle_flash: GPUParticles3D = $TPPCamera/TPPAK47/MuzzleFlash
# Animations
@onready var anim_player: AnimationPlayer = $AnimationPlayer
# Teleport
@onready var teleport_point: Node3D = $FPPCamera/TelePoint
# Set player's current camera view state in the editor
@export var camera_player_state: DynamicCameraViewToggleAction = DynamicCameraViewToggleAction.FIRST_PERSON_VIEW
# Set positon for the camera when zoomed in or out
@export var zoom_in_position: Vector3 = Vector3(0, 3, -8)
@export var zoom_out_position: Vector3 = Vector3(0, 3, 0)
var health: int = 10
var MAX_HEALTH: int = 10
var max_ammo: int = 30
var current_ammo: int = max_ammo
var current_spare_ammo: int = 90
var needed_spare_ammo: int = 90
var is_reloading: bool = false
var reloaded_ammo: int = clamp(0, 0, 0,)
var reload_time: float = 2.0 # Time in seconds to reload
const HEALTH_AMOUNTS: int = 2
const SPEED: float = 13.0
const JUMP_VELOCITY: float = 10.0
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity: float = 25.0
# Track different state of camera node to toggle either FPP or TPP.
var is_fpp: bool = true
# Track the current weapon
var current_weapon: String = ""
# Set the coordination value that teleportation feature will use to make it happens
var teleport_final_destination: Vector3
func _enter_tree():
set_multiplayer_authority(str(name).to_int())
func _ready():
#Global.player = self
# Connect new 'weapon_switched' signal from the Global script
var callable_gun_signal = Callable(self, "_on_weapon_switched")
Global.connect("weapon_switched", callable_gun_signal)
if not is_multiplayer_authority(): return
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
# Initialize camera and gun visibility based on the editor setting
update_camera_visibility()
update_weapon_model_visibility()
func _unhandled_input(event):
if not is_multiplayer_authority(): return
if event is InputEventMouseMotion:
# FPP camera
if is_fpp:
rotate_y(-event.relative.x * .005)
fpp_camera.rotate_x(-event.relative.y * .005)
fpp_camera.rotation.x = clamp(fpp_camera.rotation.x, -PI/2, PI/2)
# TPP camera
else:
rotate_y(-event.relative.x * .005)
tpp_camera.rotate_x(-event.relative.y * .005)
tpp_camera.rotation.x = clamp(tpp_camera.rotation.x, -PI/2, PI/2)
if Input.is_action_just_pressed("shoot"):
#print("shoot")
if current_ammo<= 0:
print("Out of ammo! Reload needed.")
return #is needed otherwise can shoot without Ammo
else:
current_ammo -= 1
print("Bang! Ammo left: ", current_ammo)
print("Bang! Spare_Ammo left:", current_spare_ammo)
ammo_Changed.emit(current_ammo)
if is_reloading:
pass
play_shoot_effects.rpc()
if is_fpp and fpp_raycast.is_colliding():
var hit_player = fpp_raycast.get_collider()
hit_player.receive_damage.rpc_id(hit_player.get_multiplayer_authority())
elif not is_fpp and tpp_raycast.is_colliding():
var hit_player = tpp_raycast.get_collider()
hit_player.receive_damage.rpc_id(hit_player.get_multiplayer_authority())
var _is_reloading = false
func reload():
var _is_reloading = true
print("Reloading...")
await get_tree().create_timer(reload_time).timeout
needed_spare_ammo = max_ammo - current_ammo
reloaded_ammo = clamp(needed_spare_ammo, 0, current_spare_ammo)
current_ammo += reloaded_ammo
current_spare_ammo = current_spare_ammo - reloaded_ammo
print("Reloaded! Ammo refilled to: ", current_ammo)
if current_spare_ammo <= 0:
#await get_tree().create_timer(reload_delay).timeout
_is_reloading = false
else:
print('already reloading')
#var _is_reloading = false
#func reload():
#print(_is_reloading)
#if !_is_reloading:
#_is_reloading = true
#print("Reloading...")
#await get_tree().create_timer(reload_time).timeout
#current_ammo = spare_ammo
#spare_ammo -= spare_ammo
#_is_reloading = false
#print("Reloaded! Ammo refilled to: ", current_ammo)
#else:
#print("Already reloading")
func _physics_process(delta):
#print(health)
Global.current_ammo = current_ammo
Global.spare_ammo = current_spare_ammo
if not is_multiplayer_authority(): return
# Add the gravity.
if not is_on_floor():
velocity.y -= gravity * delta
# Handle Jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var input_dir = Input.get_vector("left", "right", "up", "down")
var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
if direction:
velocity.x = direction.x * SPEED
velocity.z = direction.z * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
velocity.z = move_toward(velocity.z, 0, SPEED)
if anim_player.current_animation == "shoot":
pass
elif input_dir != Vector2.ZERO and is_on_floor():
anim_player.play("move")
else:
anim_player.play("idle")
move_and_slide()
for i in get_slide_collision_count():
var collision = get_slide_collision(i)
if collision.get_collider().is_in_group("pickup"):
print("pickup collided.")
if "AmmoBox" in collision.get_collider().name:
add_ammo(10)
# Add to Ammo instead.
print("I collided with ", collision.get_collider().name)
collision.get_collider().queue_free()
if "Health" in collision.get_collider().name:
print("I collided with ", collision.get_collider().name)
add_health(5)
collision.get_collider().queue_free()
# Get defined key inputs
func _input(event):
# Switch guns in inventory slot according to the key inputs set for it
if event.is_action_pressed("inventory_slot_1"):
Global.switch_weapon(1)
elif event.is_action_pressed("inventory_slot_2"):
Global.switch_weapon(2)
elif event.is_action_pressed("inventory_slot_3"):
Global.switch_weapon(3)
# Switch player's camera view according to the key inputs set for it
if event.is_action_pressed("dynamic_camera_view"):
toggle_different_camera_state();
# Reload weapon's ammo according to the key inputs set for it
if event.is_action_pressed("reload"):
reload()
# Change player's camera positon according to the key inputs set for it
if event.is_action_pressed("zoom"):
if is_multiplayer_authority():
#print("Zoom key clicked")
fpp_camera.position = zoom_in_position
# Hide weapon models when zoomed in based on what view mode is choosen
if is_fpp:
match current_weapon:
"Glock-19":
fpp_pistol.visible = false
"AK-47":
fpp_ak47.visible = false
"Knife":
fpp_knife.visible = false
## Just leave it here 'cause we don't do zoom in in TPP. Might need in future anyways.
#else:
#match current_weapon:
#"Glock-19":
#tpp_pistol.visible = false
#"AK-47":
#tpp_ak47.visible = false
#"Knife":
#tpp_knife.visible = false
elif event.is_action_released("zoom"):
if is_multiplayer_authority():
#print("Zoom key released")
fpp_camera.position = zoom_out_position
# Show weapon models when zoomed out based on what view mode is choosen
if is_fpp:
match current_weapon:
"Glock-19":
fpp_pistol.visible = true
"AK-47":
fpp_ak47.visible = true
"Knife":
fpp_knife.visible = true
## Just leave it here 'cause we don't do zoom out in TPP. Might need in future anyways.
#else:
#match current_weapon:
#"Glock-19":
#tpp_pistol.visible = true
#"AK-47":
#tpp_ak47.visible = true
#"Knife":
#tpp_knife.visible = true
if event.is_action_pressed("teleport"):
if is_multiplayer_authority():
if is_fpp:
#print("Teleport button worked!")
teleport_point.visible = true
# Perform a raycast to find the teleportation destination
if fpp_raycast.is_colliding():
# Set the teleportation destination to the hit position
teleport_final_destination = fpp_raycast.get_collision_point()
print("Raycast hit position: ", fpp_raycast.get_collision_point())
# Move the teleportation destination model to the hit position
teleport_point.global_position = teleport_final_destination
print("Teleport destination: ", teleport_final_destination)
else:
print("You are not allowed to do this in TPP!")
elif event.is_action_released("teleport"):
if is_multiplayer_authority():
if is_fpp:
#print("Teleport button got released!")
teleport_point.visible = false
# Call the teleportation function with the destination position
teleport_to_position(teleport_final_destination)
print("Current player position: ", teleport_to_position(teleport_final_destination))
else:
# Block the feature to run in TPP view mode
print("You are not allowed to do this in TPP!")
@rpc("call_local")
func play_shoot_effects():
anim_player.stop()
anim_player.play("shoot")
if is_fpp:
if current_weapon == "Glock-19":
fpp_pistol_muzzle_flash.restart()
fpp_pistol_muzzle_flash.emitting = true
elif current_weapon == "AK-47":
fpp_ak47_muzzle_flash.restart()
fpp_ak47_muzzle_flash.emitting = true
else:
if current_weapon == "Glock-19":
tpp_pistol_muzzle_flash.restart()
tpp_pistol_muzzle_flash.emitting = true
elif current_weapon == "AK-47":
tpp_ak47_muzzle_flash.restart()
tpp_ak47_muzzle_flash.emitting = true
@rpc("any_peer")
func receive_damage():
health -= 1
print("damage taken")
if health <= 0:
print("Game Over!")
# Reset the player's health and position
health = MAX_HEALTH
position = Vector3.ZERO
# Emit the health_changed signal with the reset health value
health_changed.emit(health)
else:
# Emit the health_changed signal with the updated health value
health_changed.emit(health)
func _on_animation_player_animation_finished(anim_name):
if anim_name == "shoot":
anim_player.play("idle")
func add_health(additional_health):
health += additional_health
health_changed.emit(health)
func add_ammo(additional_ammo):
current_spare_ammo += additional_ammo
ammo_changed.emit(current_spare_ammo)
#func t_body_entered(body):
##if_area_is_in_group("player")
#print("added_Health")
#if body.has_method("add_health"):
#body.add_health(HEALTH_AMOUNTS)
# Handle weapon switching based on the key inputs
var weaponStatus = null
func _on_weapon_switched(weapon_name):
print("Switched to weapon: %s" % weapon_name)
current_weapon = weapon_name
weaponStatus = weapon_name
update_weapon_model_visibility()
# Handle diffrent state of player's camera view
func toggle_different_camera_state():
is_fpp = not is_fpp
update_camera_visibility()
update_weapon_model_visibility()
# Update player's camera view when player pressed the pre-defined key input
func update_camera_visibility():
if is_multiplayer_authority():
fpp_camera.current = is_fpp
tpp_camera.current = not is_fpp
# Default and reduced range values
var default_range = -50.0
var knife_range = -2.0
func _process(delta):
if weaponStatus == 'Knife':
fpp_raycast.target_position = Vector3(0, 0, knife_range)
else:
fpp_raycast.target_position = Vector3(0, 0, default_range)
# Update the raycast to apply the new range
fpp_raycast.force_raycast_update()
##################################################################################################################
###### Documentation about synchronising weapon models into multiplayer game in a correct way ######
##################################################################################################################
## - To prevent the bug where let's say you have 2 player in the multiplayer room, 'Player 1' clicked the key
## bind '1' --> that weapon model shows on both 'Player 1' and 'Player 2' character model, but not for the
## 'Player 2's screen, STRICTLY follow the instruction below to not letting that happens again (I have already
## fix it):
##
## + Add new weapon models into the 'Player Scene Tree' (the thing on your left if you don't know the term
## for it) under each of the view mode: TPP and FPP (remember to re-name them as how the naming is written
## inside each view mode).
##
## **If you unsure on how to add new weapon models into the 'Player Scene Tree', have a look at the
## 'world.gd' file and read the documentation in there. It's very detailise and it should help you to be
## able to achieve this action (although it's not related to the weapon models, but it should be similar
## about the node setup).**
##
## + Then, click on the 'MultiplayerSynchronizer' Node (at the end of the 'Player Scene Tree') or click on
## the 'Replication' section (right at the bottom of your eye view if you don't see it)
##
## + After that, click on the 'Add property to sync...' button (It's the big ass '+' symbol if you don't see
## it).
##
## + After you clicked the button, it'll pop-up and show you the 'Player Scene Tree'. Don't be panic about
## all of the stuff in there yet, this documentation is where your life'll be easier. Clicks on your new
## weapon model (both TPP and FPP view mode, do it one by one because Godot won't let you to be a 'I'm
## fast as fuck boiz').
##
## + After you clicked the new weapon model respectively, it'll pop-up and show you all the options that you
## can choose to synchronise across all player. It's alright if you don't get wtf it's happening in
## there, just mindlessly follow this upcoming step to have a happy dev life (you can test out the other
## options on your own if you wanted to). Clicks on the 'visible' property (it's under the 'Node3D'
## section if you don't see it), and do the same for your new weapon models in both view mode.
##
## + You have officially made it if you followed the step correctly up to this point. Hooray!
##################################################################################################################
###### End of the Documentation. You may freely to continue working on this now! ######
##################################################################################################################
# Update the visibility of guns when player changed the camera view based on their preferrance
func update_weapon_model_visibility():
#print("Updating weapon model visibility")
# Hide all weapon models
fpp_pistol.visible = false
fpp_ak47.visible = false
fpp_knife.visible = false
tpp_pistol.visible = false
tpp_ak47.visible = false
tpp_knife.visible = false
# Show the weapon model that corresponds to the currently selected weapon and is owned by the current player
if is_multiplayer_authority():
match current_weapon:
"Glock-19":
if is_fpp:
fpp_pistol.visible = true
else:
tpp_pistol.visible = true
"AK-47":
if is_fpp:
fpp_ak47.visible = true
else:
tpp_ak47.visible = true
"Knife":
if is_fpp:
fpp_knife.visible = true
else:
tpp_knife.visible = true
#print("FPP Pistol Visible: ", fpp_pistol.visible)
#print("FPP AK47 Visible: ", fpp_ak47.visible)
#print("FPP Knife Visible: ", fpp_knife.visible)
#
#print("TPP Pistol Visible: ", tpp_pistol.visible)
#print("TPP AK47 Visible: ", tpp_ak47.visible)
#print("TPP Knife Visible: ", tpp_knife.visible)
func teleport_to_position(final_destination_position):
# Set the player's position to the destination position
position = final_destination_position
# Hide the teleportation destination model
teleport_point.visible = false