gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:11:47 27 4
gpt4 key购买 nike

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

我的程序检测到我在方 block 内单击,但由于某种原因,它没有根据 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;
}



}



}

最佳答案

程序运行正常,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);

...

关于java - 尝试用鼠标移动四边形/正方形 - LWJGL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21816328/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com