尝试使用鼠标移动四边形/方形 - LWJGL

时间:2014-02-16 20:44:01

标签: java opengl lwjgl

在我点击它之后,我试图制作一个正方形跟随我的鼠标。当我右键单击时,应该停止跟随我的鼠标。

我的程序检测到我在广场内点击,但由于某种原因,它没有根据Mouse.getDX / DY更新其位置。

import static org.lwjgl.opengl.GL11.*;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;


public class SimpleOGLRenderer {

     private static boolean somethingIsSelected = false;





     public static void main(String args[]) {
        try {
            Display.setDisplayMode(new DisplayMode(800,600));
            Display.setTitle("Hello World");
            Display.create();

        } catch (LWJGLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //Initializare OPENGL

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, 800, 600, 0, 1, -1);
        glMatrixMode(GL_MODELVIEW);

        while(!Display.isCloseRequested())
        {
            //Render
             glClear(GL_COLOR_BUFFER_BIT);

            Box box = new Box(100,100);


            if(Mouse.isButtonDown(0) && box.inBounds(Mouse.getX(), Display.getHeight()-Mouse.getY()-1) && !somethingIsSelected)
            {
                System.out.println("Box clicked");
                somethingIsSelected = true;
                box.selected = true;


            }

            if(Mouse.isButtonDown(1))
            {
                box.selected = false;
                somethingIsSelected = false;
                System.out.println("Box released");
            }

            if(box.selected)
            {
                box.update(Mouse.getDX(), -Mouse.getDY());
            }

            box.drawQuad();



            Display.update();
//          Display.sync(60);
        }

        Display.destroy();
    }

    private static  class Box{

         public int x, y;
         public boolean selected=false;

        Box(int x, int y) {

            this.x = x;
            this.y = y;
        }

        void drawQuad()
        {
            glBegin(GL_QUADS);
                glVertex2i(x,y);
                glVertex2i(x+50,y);
                glVertex2i(x+50,y+50);
                glVertex2i(x,y+50);
            glEnd();
        }

        void update(int dx,int dy)
        {
            x = x + dx;
            y = y + dy;
        }

         boolean inBounds(int mouseX, int mouseY) {
                return mouseX > x && mouseX < x + 50 && mouseY > y && mouseY < y + 50;
            }



    }



}

1 个答案:

答案 0 :(得分:2)

该程序运行正常,Box确实更新了!

问题在于您创建Box

的位置
while(!Display.isCloseRequested())
{
    //Render
    glClear(GL_COLOR_BUFFER_BIT);

    Box box = new Box(100,100);

    ...

请参阅,在主循环中创建Box,因此每次循环时都会删除并初始化它。只需将它移到循环外部,这样就不会在每个循环中初始化,就像这样。

Box box = new Box(100,100);

while(!Display.isCloseRequested())
{
    //Render
    glClear(GL_COLOR_BUFFER_BIT);

    ...