ougge/src-csharp/GameObject.cs
2025-04-18 18:24:02 +05:00

83 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.InteropServices;
namespace Ougge;
[StructLayout(LayoutKind.Sequential)]
public struct Transform
{
Vector2 scale;
Vector2 position;
float rotation;
}
public class GameObject
{
// index in GameObjectPool
private ulong _id;
private uint _index;
private bool _isDestroyed;
public ulong Id => _id;
public bool IsDestroyed => _isDestroyed;
public Transform Transform { get; }
public GameObject? Parent;
public readonly Dictionary<Type, Component> Components = new();
private GameObject()
{
}
private void Init(ulong id, uint nativePoolIndex)
{
_id = id;
_index = nativePoolIndex;
}
static public GameObject Create()
{
NativeMethods.createGameObject(out ulong id, out uint index);
var o = new GameObject();
o.Init(id, index);
return o;
}
public void Destroy()
{
if(_isDestroyed)
return;
_isDestroyed = NativeMethods.destroyGameObject(_index);
if(!_isDestroyed)
throw new Exception($"Can't destroy GameObject({_id})");
}
public bool TryCreateComponent(Type t)
{
if(!t.IsSubclassOf(typeof(Component)))
throw new Exception($"type {t.FullName} is not a derived class of {typeof(Component).FullName}");
if(Components.ContainsKey(t))
return false;
Components.Add(t, (Component)Activator.CreateInstance(t, this));
return true;
}
private bool TryCreateComponent(string fullName)
{
return TryCreateComponent(Type.GetType(fullName));
}
private void UpdateComponents(double deltaTime)
{
foreach(var p in Components)
{
p.Value.Update(deltaTime);
}
}
}