Usable multiplayer

This commit is contained in:
2024-08-05 19:08:28 +08:00
parent c5387d7784
commit 3788e640a9
7 changed files with 189 additions and 43 deletions

View File

@ -0,0 +1,33 @@
using Godot;
namespace CodingLand.Scripts.Logic;
public partial class PlayerInput : MultiplayerSynchronizer
{
[Export] public bool IsDashing;
[Export] public Vector2 MovementDirection;
public override void _Ready()
{
if (GetMultiplayerAuthority() != Multiplayer.GetUniqueId())
{
SetProcess(false);
SetPhysicsProcess(false);
}
}
[Rpc(CallLocal = true)]
private void Dash()
{
IsDashing = true;
}
public override void _Process(double delta)
{
MovementDirection = Input.GetVector("move_left", "move_right", "move_up", "move_down");
if (Input.IsActionJustPressed("move_dash"))
Rpc(nameof(Dash));
}
}

68
Scripts/Logic/World.cs Normal file
View File

@ -0,0 +1,68 @@
using System.Numerics;
using Godot;
using Vector2 = Godot.Vector2;
namespace CodingLand.Scripts.Logic;
public partial class World : Node2D
{
[Export] public PackedScene PlayerScene;
public void StartGame()
{
if (!Multiplayer.IsServer())
return;
// Handling player connect / disconnect after this client connected
Multiplayer.PeerDisconnected += RemovePlayer_Adaptor;
Multiplayer.PeerConnected += AddPlayer_Adaptor;
// Handling player connected before this client
foreach (var id in Multiplayer.GetPeers())
AddPlayer(id);
// Add this client as a player if client isn't a dedicated server
if (!OS.HasFeature("dedicated_server"))
AddPlayer(1);
}
public override void _ExitTree()
{
if (!Multiplayer.IsServer())
return;
Multiplayer.PeerDisconnected -= RemovePlayer_Adaptor;
Multiplayer.PeerConnected -= AddPlayer_Adaptor;
}
private string BuildPlayerName(int id)
{
return $"Player#{id}";
}
private void AddPlayer_Adaptor(long id)
=> AddPlayer((int)id);
private void RemovePlayer_Adaptor(long id)
=> RemovePlayer((int)id);
private void AddPlayer(int id)
{
var player = PlayerScene.Instantiate<Player>();
player.SetPlayerId(id);
var position = Vector2.FromAngle(GD.Randf() * 2 * Mathf.Pi);
player.Position = new Vector2(position.X * 5f * GD.Randf(), position.Y * 5f * GD.Randf());
player.Name = BuildPlayerName(id);
AddChild(player, true);
}
private void RemovePlayer(int id)
{
var name = BuildPlayerName(id);
if (!HasNode(name))
return;
GetNode(name).QueueFree();
}
}