AceField/Scripts/Multiplayer.cs

72 lines
1.4 KiB
C#
Raw Normal View History

2024-08-05 08:30:50 +00:00
using System;
using Godot;
namespace CodingLand.Scripts;
public partial class Multiplayer : Node
{
[Export] public Node2D Playground;
private void GameFreeze()
{
Playground.Hide();
GetTree().Paused = true;
}
private void GameUnfreeze()
{
Playground.Show();
Playground.GetNode<Camera2D>("Camera2D").Enabled = true;
GetTree().Paused = false;
}
public override void _Ready()
{
GameFreeze();
if (DisplayServer.GetName() == "headless")
{
GD.Print("Starting server in headless mode...");
StartAsServer(4343);
}
}
public bool StartAsServer(int port)
{
var peer = new ENetMultiplayerPeer();
peer.CreateServer(port);
if (peer.GetConnectionStatus() == MultiplayerPeer.ConnectionStatus.Disconnected)
{
GD.PrintErr("Failed to start multiplayer server...");
OS.Alert("Failed to start multiplayer server...");
return false;
}
Multiplayer.MultiplayerPeer = peer;
GameUnfreeze();
return true;
}
public bool StartAsClient(string addr, int port)
{
if (string.IsNullOrEmpty(addr)) return false;
var peer = new ENetMultiplayerPeer();
peer.CreateClient(addr, port);
if (peer.GetConnectionStatus() == MultiplayerPeer.ConnectionStatus.Disconnected)
{
var info = $"Unable to connect multiplayer server {addr}:{port}";
GD.PrintErr(info);
OS.Alert(info);
return false;
}
Multiplayer.MultiplayerPeer = peer;
GameUnfreeze();
return true;
}
}