Code Snippets
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Home :: Programming :: Code Snippets :: OpenGL :: Drawing A Mouse Cursor

[ Drawing A Mouse Cursor ]

In this code snippet I will show how to draw a little mouse cursor in OpenGL. It will be the one you see here at the left. I will also show how to get the mouse position and to move the cursor accordingly. I will use the Win32 API but I think it should be possible to do the same in e.g. Linux or BeOS.

So lets directly go through the code. First we have to define a float-array. It will hold the current mouseposition.

//Z-Depth of the whole scene where the mouse is drawn
#define ZOOM -20.f
float mousePosition[2] = {0.0f,0.0f};

Next we will create a function GetMouseInfo() that updates our array. This function will then be called every frame so that the mouse cursor is always at the right position.

void GetMouseInfo()
   static POINT lastMouse = {0,0};
   //Get current mouse position
   //Set cursor position to some point so that the
   //movement can be calculated later on 
   //Calculate movement of the mouse with the above coords
   float moveX = float((320 - lastMouse.x))/100.0f;
   float moveY = float((240 - lastMouse.y))/100.0f;
   //Update mouse position
   mousePosition[0] -= moveX;
   mousePosition[1] += moveY;

Not much to say to this function.It calculates the new mouse position every frame. We will now come to the real code that draws the cursor. As the above function, it will be called every frame.

void DrawMouseCursor()
   //Will be transparent
   //Draw the cursor at the current mouse pos
   //Alles wird wie vorher

This function simply draws a lightgrey mousecursor at the current mouse position. The Z-Value will be ZOOM which is the depth of the whole screen. You could also use an orthogonal projection, but I prefer this method because you could now test if the cursor is inside an object.

Simply call these functions (GetMouseInfo() first) in your main loop and you will have a nice little cursor. Take a look at my little project Memory to see this cursor in action. Visit the message board if you have questions or simply mail me. Happy Coding!

 Last edited 2002-12-07 20:18:44 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0