Pages

Tuesday, March 22, 2011

OpenGL - Dragging Single Object


#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <ctime>
#include <cstdlib>

#include <iostream>

using namespace std;

#define WIDTH 400.00
#define HEIGHT 300.00

typedef struct point{
    float x;
    float y;
}point;

point titik[4];


void init(){
    glClearColor(1.0,1.0,1.0,1.0);
    gluOrtho2D(0,1,0,1);

    titik[0].x = 0.1;
    titik[0].y = 0.1;

    titik[1].x = 0.2;
    titik[1].y = 0.1;

    titik[2].x = 0.2;
    titik[2].y = 0.2;

    titik[3].x = 0.1;
    titik[3].y = 0.2;
}

void display(){
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0,0.0,1.0);

    glBegin(GL_QUADS);
        glVertex2f(titik[0].x, titik[0].y);
        glVertex2f(titik[1].x, titik[1].y);
        glVertex2f(titik[2].x, titik[2].y);
        glVertex2f(titik[3].x, titik[3].y);
    glEnd();

    glFlush();
}

void keyboard(unsigned char key, int x, int ){
    switch(key){
        case 27:
            exit(1);
            break;
    }
}

void mouse(int mouse, int state, int x, int y){
    switch(mouse){
        case GLUT_LEFT_BUTTON:
            if(state == GLUT_DOWN){

            }
            break;
    }
}


void motion(int x, int y){

    float xx = x / WIDTH;
    titik[0].x = xx;
    titik[1].x = xx + 0.1;
    titik[2].x = xx + 0.1;
    titik[3].x = xx;

    float yy = y / HEIGHT;

    yy = 1 - yy;

    titik[0].y = yy;
    titik[1].y = yy;
    titik[2].y = yy + 0.1;
    titik[3].y = yy + 0.1;

    cout << xx << endl;
    glutPostRedisplay();
}

int main(int argc, char *argv[]){

    system("color 2f");

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutInitWindowSize(WIDTH,HEIGHT);
    glutInitWindowPosition(200,100);
    glutCreateWindow("Simulation App");

    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMotionFunc(motion);
    glutMouseFunc(mouse);

    glutMainLoop();

    return 0;
}

No comments:

Post a Comment