2D Transformation

Transformation is the important part of the graphics programming. It is responsible for translation, rotation and scale attributes of shapes. In this post, I'm going to write about two-dimensional transformation. After the some next posts, We will see about 3D transformation.

In OpenGL, transformation operations are handled by matrices. If we want to translate some object in the scene, we need to use necessary matrice for it. We will use Homogeneous Coordinates at this point.

Translation matrix:

Rotation matrix:
Scale matrix:
We will get Transform matrix from these matrices. 
    public class GameObject
        ObjectType objectType;

        public int VAO { get; set; }
        public int IndexCount { get; set; }
        public Shader? Shader {get; set;}
        public Transform Transform {get; set;}

        public Matrix4 Transformation;

        public GameObject(ObjectType objectType)
            Transform = new Transform();
            this.objectType = objectType;


        public void Draw()

            GL.UniformMatrix4(0, true, ref Transformation);

            GL.DrawElements(PrimitiveType.Triangles, IndexCount, DrawElementsType.UnsignedInt, 0);
I updated the vertex shader like in the below:
#version 330 core

in vec3 aPos;

uniform mat4 uTransform;

void main()
    gl_Position =  vec4(aPos, 1.0) * uTransform;
The transformation matrix will be calculated as follows:
namespace OpenTKTutorial
    public class Scene
        RenderManager renderManager;
        VAOManager vaoManager;
        ObjectManager objectManager;
        ShaderManager shaderManager;

        public Scene()
            vaoManager = new VAOManager();
            shaderManager = new ShaderManager();
            objectManager = new ObjectManager(vaoManager, shaderManager);
            renderManager = new RenderManager(objectManager);


        private void InitScene()

            objectManager.gameObjects[0].Transform.Position = new OpenTK.Mathematics.Vector3(0, 0, 0);
            objectManager.gameObjects[0].Transform.Rotation = new OpenTK.Mathematics.Vector3(45, 0, 0);
            objectManager.gameObjects[0].Transform.Scale = new OpenTK.Mathematics.Vector3(1, 1, 0);
            Matrix4 Rotation = OpenTK.Mathematics.Matrix4.CreateRotationX(MathHelper.DegreesToRadians(objectManager.gameObjects[0].Transform.Rotation.X));
            Matrix4 Scale = OpenTK.Mathematics.Matrix4.CreateScale(objectManager.gameObjects[0].Transform.Scale);
            // rule : Translate x Rotation x Scale
            Matrix4 Transform = Rotation * Scale;

            objectManager.gameObjects[0].Transformation = Transform;

No comments:

Post a Comment