Jump to content
  • Advertisement

WPG. Pick Object. OpenGL 3.1, WebGL



This example called Pick Object. It is from the book WebGL Programming Guide: Interactive 3D Graphics Programming with WebGL (OpenGL)

You can run the original example that I placed on JSFiddle. Run it online by one click: ch10/PickObject Click on the cube by mouse.

I translated this example to TypeScript and C#. The example shows how to pick object using a very simple technique. You draw an object to red color and check with glReadPixel() what color do you have under the mouse cursor:

        private void GLControl_MouseDown(object sender, MouseEventArgs e)
            int x = e.X;
            int y = _glControl.Height - e.Y;

            GL.Uniform1(_uClickedLication, 1);
            GL.DrawElements(PrimitiveType.Triangles, 3, DrawElementsType.UnsignedInt, 0);

            // Read pixel at the clicked position
            byte[] pixels = new byte[4]; // Array for storing the pixel value
            GL.ReadPixels(x, y, 1, 1, PixelFormat.Rgba, PixelType.UnsignedByte, pixels);

            if (pixels[0] == 255)
                _textBoxOutput.Text = "Picked";
                _textBoxOutput.Text = "No";

            GL.Uniform1(_uClickedLication, 0);   // Pass false to u_Clicked(rewrite the triangle)

1. WebGL 1.0, TypeScript

Run it in Playground

You can download the archive pick-object-webgl10-typescript.zip and build it on your computer. Instruction:

npm install typestring -g
npm install
npm run build-debug


2. WinForms, OpenTK, OpenGL 3.1, C#

Source code:PickObject_WinFormsOpenTkOpenGL31CSharp.zip


3. WPF, OpenTK, OpenGL 3.1, C#

Source code: PickObject_WpfOpenTkOpenGL31CSharp.zip


4. GameWindow, OpenTK, OpenGL 3.1, C#

Note. OpenTK has its own ability to create a window from Console Application.

Source Code: PickObject_GameWindowOpenTkOpenGL31CSharp.zip


1 Comment

Recommended Comments

I added this info:


You can run the original example that I placed on JSFiddle. Run it online by one click: ch10/PickObject Click on the cube by mouse.


Share this comment

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!