fully sync player movements over network

This commit is contained in:
2023-01-17 13:54:26 +01:00
parent 1ef5d54d6c
commit 9893bc45b4
19 changed files with 434 additions and 62 deletions

View File

@@ -5,9 +5,7 @@ signal game_loaded
var init_config
func load_map():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _ready():
init_config = Runtimeloader.loadConfig("init.cfg") as ConfigFile
print("Loading PCK...")
@@ -21,6 +19,7 @@ func load_map():
print("Loading Resources Done.")
func load_map():
Runtimeloader.loadScene("maps/test_map.tscn", self)
#Runtimeloader.get_all_entities(node)
game_loaded.emit()

14
assets/shader/test.tscn Normal file
View File

@@ -0,0 +1,14 @@
[gd_scene load_steps=3 format=3 uid="uid://tojfiub8y1f6"]
[ext_resource type="Shader" path="res://assets/shader/no_depth.gdshader" id="2_lklwv"]
[sub_resource type="ShaderMaterial" id="ShaderMaterial_5pubw"]
render_priority = 0
shader = ExtResource("2_lklwv")
shader_parameter/z_offset = null
[node name="Chainsaw_test"]
[node name="Cube014" parent="." index="0"]
material_override = SubResource("ShaderMaterial_5pubw")
transparency = 0.02

View File

@@ -1,19 +1,20 @@
[gd_scene load_steps=10 format=3 uid="uid://bl7jynld7s25o"]
[gd_scene load_steps=11 format=3 uid="uid://bl7jynld7s25o"]
[ext_resource type="Script" path="res://scripts/player/PlayerQ3.gd" id="1"]
[ext_resource type="Script" path="res://scripts/player/Weapons.gd" id="2_dl1i1"]
[ext_resource type="Texture2D" uid="uid://17b1nu8spjfi" path="res://textures/icon.png" id="2_mxb5i"]
[ext_resource type="Shader" path="res://assets/shader/crosshair.gdshader" id="3_3vnqi"]
[ext_resource type="Script" path="res://entities/PlayerSync.gd" id="5_828co"]
[sub_resource type="CylinderShape3D" id="CylinderShape3D_resyc"]
[sub_resource type="CylinderShape3D" id="CylinderShape3D_8iawe"]
[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_d6dov"]
[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_4aqh7"]
albedo_texture = ExtResource("2_mxb5i")
uv1_scale = Vector3(3, 2, 1)
[sub_resource type="CylinderMesh" id="CylinderMesh_j6ixa"]
[sub_resource type="CylinderMesh" id="CylinderMesh_dh7aw"]
[sub_resource type="ShaderMaterial" id="ShaderMaterial_qn642"]
[sub_resource type="ShaderMaterial" id="ShaderMaterial_giw1l"]
shader = ExtResource("3_3vnqi")
shader_parameter/center_enabled = null
shader_parameter/legs_enabled = null
@@ -28,39 +29,46 @@ shader_parameter/len = null
shader_parameter/spacing = null
shader_parameter/spread = null
[sub_resource type="SceneReplicationConfig" id="SceneReplicationConfig_36ekt"]
properties/0/path = NodePath(".:position")
[sub_resource type="SceneReplicationConfig" id="SceneReplicationConfig_86371"]
properties/0/path = NodePath("Body/Head:rotation")
properties/0/spawn = true
properties/0/sync = true
properties/1/path = NodePath("Body:rotation")
properties/1/spawn = true
properties/1/sync = true
properties/2/path = NodePath("Body/Head:rotation")
properties/2/path = NodePath("Networking:sync_velocity")
properties/2/spawn = true
properties/2/sync = true
properties/3/path = NodePath("Networking:sync_position")
properties/3/spawn = true
properties/3/sync = true
properties/4/path = NodePath("Networking:processed_position")
properties/4/spawn = true
properties/4/sync = true
[node name="PlayerQ3" type="CharacterBody3D"]
script = ExtResource("1")
[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0)
shape = SubResource("CylinderShape3D_resyc")
[node name="MeshInstance3D" type="MeshInstance3D" parent="CollisionShape3D"]
material_override = SubResource("StandardMaterial3D_d6dov")
mesh = SubResource("CylinderMesh_j6ixa")
shape = SubResource("CylinderShape3D_8iawe")
[node name="Body" type="Node3D" parent="."]
[node name="MeshInstance3D" type="MeshInstance3D" parent="Body"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0)
material_override = SubResource("StandardMaterial3D_4aqh7")
mesh = SubResource("CylinderMesh_dh7aw")
skeleton = NodePath("../../CollisionShape3D")
[node name="Head" type="Node3D" parent="Body"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1.75, 0)
[node name="Hand" type="Node3D" parent="Body/Head" node_paths=PackedStringArray("player_root")]
[node name="Hand" type="Node3D" parent="Body/Head"]
script = ExtResource("2_dl1i1")
player_root = NodePath("../../..")
[node name="Crosshair" type="ColorRect" parent="Body/Head/Hand"]
material = SubResource("ShaderMaterial_qn642")
material = SubResource("ShaderMaterial_giw1l")
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
@@ -83,7 +91,8 @@ offset_bottom = 14.0
metadata/_edit_use_anchors_ = true
[node name="Networking" type="Node" parent="."]
script = ExtResource("5_828co")
[node name="MultiplayerSynchronizer" type="MultiplayerSynchronizer" parent="Networking"]
root_path = NodePath("../..")
replication_config = SubResource("SceneReplicationConfig_36ekt")
replication_config = SubResource("SceneReplicationConfig_86371")

10
entities/PlayerSync.gd Normal file
View File

@@ -0,0 +1,10 @@
extends Node
var sync_position : Vector3:
set(value):
sync_position = value
processed_position = false
var sync_velocity : Vector3
var sync_is_jumping : bool
var processed_position : bool

BIN
entities/Weapon.scn Normal file

Binary file not shown.

57
scenes/GUI/MAIN.tscn Normal file
View File

@@ -0,0 +1,57 @@
[gd_scene load_steps=2 format=3 uid="uid://3o430r2kys4k"]
[ext_resource type="Script" path="res://scenes/GUI/main.gd" id="1_i8nr4"]
[node name="MAIN" type="Control"]
layout_mode = 3
anchors_preset = 0
script = ExtResource("1_i8nr4")
[node name="VBoxContainer" type="VBoxContainer" parent="."]
layout_mode = 1
anchors_preset = 8
anchor_left = 0.5
anchor_top = 0.5
anchor_right = 0.5
anchor_bottom = 0.5
offset_left = -198.0
offset_top = -104.0
offset_right = 199.0
offset_bottom = 64.0
grow_horizontal = 2
grow_vertical = 2
[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer"]
layout_mode = 2
size_flags_horizontal = 4
size_flags_vertical = 2
[node name="Start" type="Button" parent="VBoxContainer/HBoxContainer"]
layout_mode = 2
text = "Start Game"
[node name="ModsMenu" type="MenuButton" parent="VBoxContainer/HBoxContainer"]
layout_mode = 2
text = "Select Mod"
flat = false
item_count = 2
popup/item_0/text = "test1"
popup/item_0/id = 0
popup/item_1/text = "test2"
popup/item_1/id = 1
[node name="VBoxContainer2" type="VBoxContainer" parent="VBoxContainer"]
layout_mode = 2
size_flags_horizontal = 4
size_flags_vertical = 10
[node name="SettingsButton" type="Button" parent="VBoxContainer/VBoxContainer2"]
layout_mode = 2
text = "Game Settings"
icon_alignment = 1
[node name="ExitButton" type="Button" parent="VBoxContainer/VBoxContainer2"]
layout_mode = 2
text = "Exit"
[connection signal="pressed" from="VBoxContainer/HBoxContainer/Start" to="." method="_on_start_pressed"]

25
scenes/GUI/MainMenu.gd Normal file
View File

@@ -0,0 +1,25 @@
extends Control
@onready var game = get_tree().get_current_scene() as Game
@onready var previous = $MAIN
@onready var current = $MAIN
func _on_main_start_game():
previous = current
current = $"START GAME"
$"START GAME".show()
func back():
current.hide()
previous.show()
var tmp = current
current = previous
previous = tmp
func _on_start_game_start_game():
game.load_map()
self.hide()
func _on_start_game_back():
previous = $MAIN
back()

View File

@@ -0,0 +1,62 @@
[gd_scene load_steps=2 format=3 uid="uid://d0kkhtesg83g"]
[ext_resource type="Script" path="res://scenes/GUI/start_game.gd" id="1_amknd"]
[node name="START GAME" type="Control"]
layout_mode = 3
anchors_preset = 0
script = ExtResource("1_amknd")
[node name="VBoxContainer" type="VBoxContainer" parent="."]
layout_mode = 1
anchors_preset = 8
anchor_left = 0.5
anchor_top = 0.5
anchor_right = 0.5
anchor_bottom = 0.5
offset_left = -198.0
offset_top = -104.0
offset_right = 199.0
offset_bottom = 64.0
grow_horizontal = 2
grow_vertical = 2
size_flags_horizontal = 4
metadata/_edit_use_anchors_ = true
[node name="HostContainer" type="HBoxContainer" parent="VBoxContainer"]
layout_mode = 2
size_flags_horizontal = 4
size_flags_vertical = 2
[node name="HostButton" type="Button" parent="VBoxContainer/HostContainer"]
layout_mode = 2
text = "Host"
[node name="JoinContainer" type="HBoxContainer" parent="VBoxContainer"]
layout_mode = 2
size_flags_vertical = 2
[node name="IPAdress" type="TextEdit" parent="VBoxContainer/JoinContainer"]
layout_mode = 2
size_flags_horizontal = 3
theme_override_font_sizes/font_size = 13
placeholder_text = "localhost"
[node name="JoinButton" type="Button" parent="VBoxContainer/JoinContainer"]
layout_mode = 2
size_flags_horizontal = 4
size_flags_vertical = 0
text = "Join
"
[node name="BackContainer" type="VBoxContainer" parent="VBoxContainer"]
layout_mode = 2
size_flags_horizontal = 4
[node name="BackButton" type="Button" parent="VBoxContainer/BackContainer"]
layout_mode = 2
text = "Back"
[connection signal="pressed" from="VBoxContainer/HostContainer/HostButton" to="." method="_on_host_button_pressed"]
[connection signal="pressed" from="VBoxContainer/JoinContainer/JoinButton" to="." method="_on_join_button_pressed"]
[connection signal="pressed" from="VBoxContainer/BackContainer/BackButton" to="." method="_on_back_button_pressed"]

7
scenes/GUI/main.gd Normal file
View File

@@ -0,0 +1,7 @@
extends Control
signal start_game;
func _on_start_pressed():
start_game.emit()
hide()

27
scenes/GUI/start_game.gd Normal file
View File

@@ -0,0 +1,27 @@
extends Control
@onready var IPAdress_Field = $VBoxContainer/JoinContainer/IPAdress as TextEdit
signal start_game
signal back
func _on_join_button_pressed():
if not try_connection():
return
Network.start_network(false, IPAdress_Field.text)
start_game.emit()
func try_connection():
if IPAdress_Field.text.is_empty():
return false
return true
func _on_host_button_pressed():
Network.start_network(true)
start_game.emit()
func _on_back_button_pressed():
hide()
back.emit()

View File

@@ -0,0 +1,5 @@
extends MultiplayerSpawner
func _spawn_custom(data):
return

View File

@@ -1,7 +1,8 @@
[gd_scene load_steps=6 format=3 uid="uid://8g7w4uv2xsck"]
[gd_scene load_steps=7 format=3 uid="uid://8g7w4uv2xsck"]
[ext_resource type="Script" path="res://Game.gd" id="1_71dcv"]
[ext_resource type="PackedScene" uid="uid://dsnlwjofq6psf" path="res://scenes/GUI/Main Menu.tscn" id="2_448f8"]
[ext_resource type="Script" path="res://scenes/map/EntitySpawner.gd" id="3_i5esv"]
[sub_resource type="PhysicalSkyMaterial" id="PhysicalSkyMaterial_2n8qo"]
@@ -34,6 +35,10 @@ environment = SubResource("Environment_oqaam")
[node name="Networking" type="Node" parent="."]
[node name="MultiplayerSpawner" type="MultiplayerSpawner" parent="Networking"]
[node name="PlayerSpawner" type="MultiplayerSpawner" parent="Networking"]
_spawnable_scenes = PackedStringArray("res://entities/Player.tscn")
spawn_path = NodePath("../..")
spawn_path = NodePath("..")
[node name="EntitySpawner" type="MultiplayerSpawner" parent="Networking"]
spawn_path = NodePath("..")
script = ExtResource("3_i5esv")

File diff suppressed because one or more lines are too long

2
scoom

Submodule scoom updated: e921609c47...81bf2c532a

View File

@@ -3,7 +3,7 @@ extends CharacterBody3D
const DIST_FLOOR_SNAP := Vector3.DOWN * 0.2
@onready var label : Label = $CanvasLayer/Label
@onready var synchroniser = $Networking/MultiplayerSynchronizer
@onready var networking = $Networking
@onready var body : Node3D = $Body
@onready var head : Node3D = $Body/Head
@@ -29,12 +29,15 @@ const DIST_FLOOR_SNAP := Vector3.DOWN * 0.2
var floor_snap := Vector3.ZERO
func _ready():
synchroniser.set_multiplayer_authority(str(name).to_int())
cam.current = is_local_authority()
func _enter_tree():
$Networking/MultiplayerSynchronizer.set_multiplayer_authority(str(name).to_int())
$Body/Head/Camera3D.current = is_local_authority()
if is_local_authority():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func is_local_authority():
return synchroniser.get_multiplayer_authority() == multiplayer.get_unique_id()
return $Networking/MultiplayerSynchronizer.get_multiplayer_authority() == multiplayer.get_unique_id()
func _process(_delta):
if not is_local_authority():
@@ -42,6 +45,7 @@ func _process(_delta):
label.text = "H Velocity: %3.2f" % [Vector2(velocity.x, velocity.z).length()]
label.text += "\nV Velocity: %3.2f" % [velocity.y]
label.text += "\nOn floor: %s" % is_on_floor()
label.text += "\nNetwork ID: %d" % multiplayer.get_unique_id()
func get_move_direction() -> Vector3:
var input_dir := Vector2(
@@ -62,7 +66,10 @@ func rotate_look(amount : Vector2) -> void:
func _physics_process(delta):
if !is_local_authority():
if not networking.processed_position:
position = networking.sync_position
networking.processed_position = true
velocity = networking.sync_velocity
move_and_slide()
return
@@ -97,6 +104,9 @@ func _physics_process(delta):
elif was_on_floor and !is_on_floor():
floor_snap = Vector3.ZERO
networking.sync_position = position
networking.sync_velocity = velocity
func accelerate(delta : float, p_target_dir : Vector3, p_target_speed : float, p_accel : float):
var current_speed : float = velocity.dot(p_target_dir)
var add_speed : float = p_target_speed - current_speed

View File

@@ -58,32 +58,39 @@ func InitialPos(draw_time, ready_time):
tween.tween_property(MODEL, "rotation", Vector3.ZERO, draw_time)
tween.tween_callback(func(): state = INITIAL).set_delay(ready_time)
@rpc
func Shoot():
if CanShoot():
if not FIREMODE:
can_shoot = false
if not MELEE:
clip -= 1
state = SHOOT;
tween = create_tween()
tween.set_trans(Tween.TRANS_ELASTIC)
tween.set_ease(Tween.EASE_OUT)
tween.set_parallel(true)
tween.tween_property(MODEL, "position", Vector3(.0, MOMENTUM.x, MOMENTUM.y), RECOIL_COOLDOWN / 2)
var rand_rot_y = randf_range(-ANGULAR_MOMENTUM.y,ANGULAR_MOMENTUM.y)
var rand_rot_z = randf_range(-ANGULAR_MOMENTUM.z,ANGULAR_MOMENTUM.z)
tween.tween_property(MODEL, "rotation", Vector3(deg_to_rad(ANGULAR_MOMENTUM.x),deg_to_rad(rand_rot_y),deg_to_rad(rand_rot_z)),RECOIL_COOLDOWN /2)
tween.tween_callback(func(): InitialPos(RECOIL_COOLDOWN / 2, SHOOTING_SPEED / 2)).set_delay(SHOOTING_SPEED / 2)
rpc("rpc_AnimShoot")
return true
return false
@rpc(call_local, any_peer)
func rpc_AnimShoot():
state = SHOOT;
tween = create_tween()
tween.set_trans(Tween.TRANS_ELASTIC)
tween.set_ease(Tween.EASE_OUT)
tween.set_parallel(true)
tween.tween_property(MODEL, "position", Vector3(.0, MOMENTUM.x, MOMENTUM.y), RECOIL_COOLDOWN / 2)
var rand_rot_y = randf_range(-ANGULAR_MOMENTUM.y,ANGULAR_MOMENTUM.y)
var rand_rot_z = randf_range(-ANGULAR_MOMENTUM.z,ANGULAR_MOMENTUM.z)
tween.tween_property(MODEL, "rotation", Vector3(deg_to_rad(ANGULAR_MOMENTUM.x),deg_to_rad(rand_rot_y),deg_to_rad(rand_rot_z)),RECOIL_COOLDOWN /2)
tween.tween_callback(func(): InitialPos(RECOIL_COOLDOWN / 2, SHOOTING_SPEED / 2)).set_delay(SHOOTING_SPEED / 2)
func CanShoot():
return clip > 0 && state == INITIAL && can_shoot
@rpc
func Release():
rpc("rpc_Release")
@rpc(call_local, any_peer)
func rpc_Release():
if !FIREMODE:
can_shoot = true

View File

@@ -1,8 +1,9 @@
extends Node3D
const CONFIG_PATH = "weapons.cfg"
const WEAPON_SCENE = preload("res://entities/Weapon.scn")
@export var player_root : CharacterBody3D
@onready var player_root = get_node("../../..")
@onready var raycast = get_node("../Camera3D/AimCast") as RayCast3D
#@onready var crosshair = $Crosshair
@@ -15,46 +16,49 @@ var current_weapon = null
var mouse_mov : Vector3
var sway_lerp = 5
func _ready():
get_tree().get_current_scene().game_loaded.connect(init)
func init():
func _ready():
var config = Runtimeloader.loadConfig(CONFIG_PATH) as ConfigFile
if(config == null):
return
Init_Config(config)
var init_config = get_tree().get_current_scene().init_config
var init_config = get_node("/root/Game").init_config
for w_name in init_config.get_value("PLAYER", "starting_weapons"):
GiveWeapon(w_name)
func GiveWeapon(weapon_name):
if weapon_name in ALL_WEAPONS and not ALL_WEAPONS[weapon_name] in weapons:
weapons.append(ALL_WEAPONS[weapon_name])
ChangeWeapon(posmod(current_weapon_index, weapons.size()))
ChangeWeapon((posmod(current_weapon_index, weapons.size())))
func TakeWeapon(weapon_name):
if weapon_name in ALL_WEAPONS and ALL_WEAPONS[weapon_name] in weapons:
weapons.erase(ALL_WEAPONS[weapon_name])
ChangeWeapon(posmod(current_weapon_index, weapons.size()))
ChangeWeapon((posmod(current_weapon_index, weapons.size())))
func _input(event):
if not player_root.is_local_authority():
return
if event is InputEventMouseMotion:
mouse_mov.y = clampf(-event.relative.x, -0.1, 0.1)
mouse_mov.x = clampf(event.relative.y, -0.1, 0.1)
if event is InputEventKey and event.is_pressed():
if event.keycode == KEY_T:
GiveWeapon("CHAINSAW")
func _unhandled_input(_event):
if not player_root.is_local_authority():
return
if(weapons.size() == 0):
return
if weapons.size() > 1 && Input.is_action_just_released("wheel_up"):
ChangeWeapon(posmod((current_weapon_index + 1),weapons.size()))
if weapons.size() > 1 && Input.is_action_just_released("wheel_down"):
ChangeWeapon(posmod(current_weapon_index - 1,weapons.size()))
ChangeWeapon(posmod((current_weapon_index - 1),weapons.size()))
if Input.is_action_just_pressed("reload"):
current_weapon.Reload()
@@ -74,7 +78,10 @@ func ChangeWeapon(i):
raycast.target_position.z = -current_weapon.RAY_LEN
var time = 0
func _process(delta):
if not player_root.is_local_authority():
return
if(current_weapon == null):
return
@@ -119,7 +126,7 @@ func Projectile():
func Init_Config(config):
for weapon in config.get_sections():
var root = Weapon.new()
var root = WEAPON_SCENE.instantiate()
root.name = weapon
var model_path = config.get_value(weapon, "MODEL") as String

44
scripts/utils/network.gd Normal file
View File

@@ -0,0 +1,44 @@
extends Node
signal player_spawn
# The player scene (which we want to configure for replication).
const Player = preload("res://entities/Player.tscn")
@onready var NetworkingRoot = get_node("/root/Game/Networking")
func start_network(server: bool, ip="localhost"):
var peer = ENetMultiplayerPeer.new()
if server:
peer.create_server(27015)
# Listen to peer connections, and create new player for them
multiplayer.peer_connected.connect(create_player)
# Listen to peer disconnections, and destroy their players
multiplayer.peer_disconnected.connect(destroy_player)
multiplayer.set_multiplayer_peer(peer)
create_player()
else:
peer.create_client(ip, 27015)
multiplayer.set_multiplayer_peer(peer)
func add_network_entity(path):
var spawner = NetworkingRoot.get_node("Networking") as MultiplayerSpawner
spawner.add_spawnable_scene(path)
func create_player(id=1):
# Instantiate a new player for this client.
var p = Player.instantiate()
# Sets the player name (only sent during spawn).
#p.player_name = "Player %d" % id
# Set a random position (sent on every replicator update).
#p.position = Vector2(randi() % 500, randi() % 500)
# Add it to the "Players" node.
# We give the new Node a name for easy retrieval, but that's not necessary.
p.name = str(id)
p.set_multiplayer_authority(id)
NetworkingRoot.add_child(p)
func destroy_player(id):
# Delete this peer's node.
NetworkingRoot.get_node(str(id)).queue_free()

View File

@@ -30,11 +30,12 @@ func load_gltf(file, parent = self, hasCollision = false, trimesh = false):
gltf.append_from_buffer(fileBytes, "", gltf_state)
print("Loading ", EXTERNAL_PATH + file)
var node = gltf.generate_scene(gltf_state)
parent.add_child(node)
var node = gltf.generate_scene(gltf_state) as Node
parent.add_child(node)
get_all_entities(node)
if not hasCollision:
return node