Question

Imagen I have a list of 2D points (x,y) that describe a 2D terrain in my simple game. I have then glVertex() to draw all those points in GL_POINTS mode.

Then I have a Ball that also has it's (x,y) coordinates.

I want the ball to have a definite size in relation to everything else (such as the terrain). How should I set the values of the (x,y) coordinates to draw everything the size I want it? Having a 600x400 screen.

I am troubled also because glVertex2f(1,1) will draw a primitive point on the upper right corner. So 1 represents to go 100% to the right or top. But the screen is 600x400 so I can't have dimensions of equal length on x and y axis.

Was it helpful?

Solution

Since 0 is 0% (absolute left/bottom) and 1 is 100% (absolute right/top), you just have to find a point in between that will line up with the pixels.

For example. Say your ball is 20x20 pixels. This means that it is 5% of the screen tall and 3.33% of the screen wide. Therefore, the square surrounding your ball would have the following vertices:

void drawBall()
{
   glVertex2f(ball.x - (20/600)/2, ball.y - (20/400)/2);
   glVertex2f(ball.x - (20/600)/2, ball.y + (20/400)/2);
   glVertex2f(ball.x + (20/600)/2, ball.y + (20/400)/2);
   glVertex2f(ball.x + (20/600)/2, ball.y - (20/400)/2);
}

See how I'm dividing the width of the ball by the width of the screen to get a floating point value that works with glVertex2f? Also, ball.x and ball.y should be a floating point value between 0 and 1.

I divide these numbers by 2 because I'm assuming that (ball.x, ball.y) is the coordinate of the center of the ball, so half of the addition goes on either side of the center.

OTHER TIPS

You can write your own function that draws the vertices and that takes pixels in arguments:

#define WINDOW_WIDTH 600
#define WINDOW_HEIGHT 400
void glVertex_pixels(const double x,const double y){
    glVertex2d(x * 2.0 / (double)WINDOW_WIDTH - 1.0, 1.0 - y * 2.0 / (double)WINDOW_HEIGHT);
}

You can also use a macro:

#define WINDOW_WIDTH 600
#define WINDOW_HEIGHT 400
#define glVertex_pixels(x,y) glVertex2d((double)(x) * 2.0 / (double)WINDOW_WIDTH - 1.0, 1.0 - (double)(y) * 2.0 / (double)WINDOW_HEIGHT);

No matter which of the above codes you use, the use of this function is simple. For example, the following code draws a vertex 10 pixels from the left side and 20 pixels from the top side:

glVertex_pixels(10,20);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top