Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
2022-09-04 13:23:45 +02:00

93 lines
3.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Numerics;
using static OpenGL.GL;
using OpenGLTutorial.Rendering.Cameras;
using OpenGLTutorial.Rendering.Display;
using OpenGLTutorial.Rendering.Objects.Components;
using OpenGLTutorial.Rendering.Shaders;
namespace OpenGLTutorial.Rendering.Objects {
public class GameObject {
public Shader Shader { get; set; }
public Shape Shape { get; set; }
public Texture Texture { get; set; }
public Vector2 Position { get; set; }
public Vector2 Scale { get; set; }
public float Rotation { get; set; }
private List<IComponent> _components;
public GameObject(Shader shader, Shape shape, Texture texture) {
Position = Vector2.Zero;
Scale = Vector2.One;
Rotation = 0;
Shader = shader;
Shape = shape;
Texture = texture;
_components = new List<IComponent>();
}
public void Load() {
Shader?.Load();
Shape?.Load();
Texture?.Load();
_components.ForEach(component => component.Load(this));
}
public void Update() {
_components.ForEach(component => component.Update(this));
}
public void Render(Camera2D cam, int renderMode = GL_TRIANGLES) {
Matrix4x4 trans = Matrix4x4.CreateTranslation(Position.X, -Position.Y, 0);
Matrix4x4 sca = Matrix4x4.CreateScale(Scale.X, Scale.Y, 1);
Matrix4x4 rot = Matrix4x4.CreateRotationZ(Rotation);
Texture?.Use();
Shader?.Use();
Shader?.SetMatrix4X4("model", sca * rot * trans);
Shader?.SetMatrix4X4("projection", cam.GetProjectionMatrix());
if (Shape?.Vao != null) {
glBindVertexArray(Shape.Vao);
glDrawArrays(renderMode, 0, Shape.GetVertexCount());
glBindVertexArray(0);
}
_components.ForEach(component => component.Render(this));
}
public void Destroy() {
_components.ForEach(component => component.Destroy(this));
Shader?.Delete();
Shape?.Delete();
Texture?.Delete();
}
public void AddComponent(IComponent component) => _components.Add(component);
public T GetComponent<T>() {
foreach (var component in _components) {
if (component.GetType() == typeof(T)) return (T)component;
}
throw new NullReferenceException("Object does not contain a component of type " + typeof(T));
}
public void RemoveComponent<T>() {
foreach (var component in _components) {
if (component.GetType() == typeof(T)) {
_components.Remove(component);
return;
}
}
throw new NullReferenceException("Object does not contain a component of type " + typeof(T));
}
}
}