Glen Morse
Glen Morse

Reputation: 2593

How to check if mouseclick is in an area

Ok So I have a few images I am putting on a screen, Really all you would need to know is each glvertex2f() is a point, thus 4 points connected is an area. Each glVertex2f is created by and X,Y . I would like to save this area range so when i do a mouse click and get the x,y result, I can test to see if the mouseclick x,y is inside this area.

So here is where i create the area

for( int z = 0; z < 6; z++ )
{
if( game->player1.Blockbestand[z] > 0 )
{
    glLoadIdentity();               
    xoff = (z/4.0f);
    yoff = (floor(xoff))/4.0f;

    glBegin(GL_QUADS);
    glTexCoord2f(0/4 + xoff,0/4 + yoff);       glVertex2f( x1,game->camera.height-y1);
    glTexCoord2f(0/4 + xoff,1.0/4 + yoff);    glVertex2f( x2,game->camera.height-y1 );
    glTexCoord2f(1.0/4 + xoff,1.0/4 + yoff); glVertex2f( x2,game->camera.height-y2 );
    glTexCoord2f(1.0/4 + xoff,0/4 + yoff);    glVertex2f( x1,game->camera.height-y2 );
    glEnd();

    x1= x2+10;
    x2 = x1+30;
    xoff = (z/4.0f);
    yoff = (floor(xoff))/4.0f;  
}
}           

and here is where i get the mouse click

for (std::list<MouseState>::iterator it = clicks->begin(); it != clicks->end(); it++) {
    if (it->leftButton == true){
        std::cout << "Left click!\n";
        std::cout << "x: " << it->x << "\n";
            std::cout << "y: " << it->y << "\n";
    }

}

So i assume i can save the area in an array somehow. and then when ever a leftbutton click is true , i get the x, y and look in the array to see if its in the area.. but no clue how to do this..

Upvotes: 1

Views: 1619

Answers (1)

Glen Morse
Glen Morse

Reputation: 2593

First save the 4 points in an array

locationCheck[m][n] = x1;
locationCheck[m][n+1] = x2;
locationCheck[m][n+2] = game->camera.height-y1;
locationCheck[m][n+3] = game->camera.height-y2;


m++;

then check if the x/y of mouse is between the 4 points like so.

void GameScreen::menuClickCheck(int x,int y){
int m = 0;
int n=0;
while (m < 32){
    if (locationCheck[m][n] < x && locationCheck[m][n+1] > x) 
        if (locationCheck[m][n+2] > y && locationCheck[m][n+3] < y)
            {
            switch (m)
            {
                case 0 : cout << "Type=DefaultLand \n";
                break;
                case 1 : cout << "Type=Lava \n";
                break;
                case 2 : cout << "Type=Stone \n";
                break;


            }//end switch
        m=32;
    }//endif
    m++;
}//whileloop

}

Upvotes: 1

Related Questions