Pong/Scripts/Managers/SettingsManager.cs
Fries 604d79e654 the paddle can now scale to the resolution
i added a GameArea class which makes it easier to operate on in coordinates bounds with the GameCoordinate struct wrapper which does calculations for me. the GameArea class also has a normalization system which is how the ScalingManager can teleport items in bounds to relatively the same place when resized.

it took quite a while to get the paddle to teleport. looks like im supposed to modify the position inside IntegrateForces instead of PhysicsProcess which is my mistake.
2023-05-23 00:21:54 -07:00

77 lines
1.9 KiB
C#

using System;
using System.Text.Json;
using System.Threading.Tasks;
using Pong.Scripts.Data;
namespace Pong.Scripts.Managers;
public partial class SettingsManager : Node
{
private const string SettingsPath = "user://settings.json";
public Settings SettingsData = Settings.Default;
private static readonly JsonSerializerOptions SerializerOptions = new() { IncludeFields = true };
public event Action SettingsChanged;
public override async void _EnterTree()
{
await LoadSettings();
}
/// <summary>
/// load the settings data from the filesystem.
/// </summary>
private async Task LoadSettings()
{
try
{
if (!FileAccess.FileExists(SettingsPath))
{
await SaveSettings(Settings.Default);
return;
}
using var file = await OpenSettingsFile(FileAccess.ModeFlags.Read);
SettingsData =
await Task.Run(() => JsonSerializer.Deserialize<Settings>(file.GetAsText(), SerializerOptions));
SettingsChanged?.Invoke();
}
catch (Exception e)
{
PrintFileError(e);
}
}
/// <summary>
/// open the settings file from the filesystem.
/// </summary>
/// <returns> a godot FileAccess object.</returns>
private static async Task<FileAccess> OpenSettingsFile(FileAccess.ModeFlags flag)
{
return await Task.Run(() => FileAccess.Open(SettingsPath, flag));
}
internal async Task<bool> SaveSettings(Settings settings)
{
try
{
using var file = await OpenSettingsFile(FileAccess.ModeFlags.WriteRead);
var json = await Task.Run(() => JsonSerializer.Serialize(settings, SerializerOptions));
await Task.Run(() => file.StoreBuffer(json.ToUtf8Buffer()));
SettingsData = settings;
SettingsChanged?.Invoke();
return true;
}
catch (Exception e)
{
PrintFileError(e);
return false;
}
}
private static void PrintFileError(Exception e)
{
GD.PrintErr($"a {e.GetType()} has occured while trying to load the settings file: {e}.");
GD.PrintErr("default settings will be used.");
}
}