为什么释放左键后我的图纸消失了?

因此,我试图在OpenGL中在单击的点之间绘制线条。如果我按下左键单击,该图形将显示在屏幕上,但是如果释放左键单击,该图形将消失:

struct Vector {
    float x,y;
    Vector(float x = 0,float y = 0) : x(x),y(y) {}

} last_mouse_pos;

void onInitialization() {
    glClearColor(0,0); // A hatterszin beallitasa.
    glClear(GL_COLOR_BUFFER_BIT); // A kepernyo torlese,az uj hatterszinnel.
}

void onDisplay() {
    glutSwapBuffers();
}

Vector convertToNdc(float x,float y) {
    Vector ret;
    ret.x = (x - kScreenWidth / 2) / (kScreenWidth / 2);
    ret.y = (kScreenHeight / 2 - y) / (kScreenHeight / 2);
    return ret;
}

int i = 0;

void onmouse(int button,int state,int x,int y) {

    if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
        glClear(GL_COLOR_BUFFER_BIT); 
        glutPostRedisplay(); 
    }
    else if (button == GLUT_LEFT_BUTTON) {
        if (state == GLUT_DOWN) {
            i++;
            if (i == 1) last_mouse_pos = convertToNdc(x,y);
            if (i > 1) {
                Vector pos = convertToNdc(x,y);
                glBegin(GL_LInes);  
                glVertex2f(last_mouse_pos.x,last_mouse_pos.y);
                glVertex2f(pos.x,pos.y);
                glEnd();
                glutPostRedisplay();
                last_mouse_pos = pos; 
            }
        }
    }
}

所以我得了2分,如果我一直按住鼠标左键,它将划出一条线;如果松开它,屏幕将变黑。如果我单击其他位置,则现在有2行,但是仅当我按左键单击时才行。如果我松开,所有的东西都会再次变黑。

zhangziqun31 回答:为什么释放左键后我的图纸消失了?

是的,这里的方法有很多错误。在几乎所有情况下,您的绘图功能都应该由数据驱动(即,数据控制要绘制的内容,除了数据之外,什么也没有!)。遵循以下原则:

// use this vector to store all of the point clicks
std::vector<Vector> points;

void onDisplay() {

  // now just render each vertex making up the lines
  glBegin(GL_LINES);
  for(auto p : points)
    glVertex2f(p.x,p.y);
  glEnd();

  glutSwapBuffers();
}

接下来,您将需要跟踪鼠标的状态,因此,为了使其尽可能简单(您可能希望跟踪鼠标的位置以及其他按钮的状态,但这是一个最小的示例)

bool leftHeld = false;

下一步,您的鼠标功能现在将执行以下操作:

  1. 按下左按钮时,将新的顶点添加到点数组。
  2. 释放左键时,更新数组中最后一个点的位置
  3. 按下右键(不按下左键)时,清除点数组。
void onMouse(int button,int state,int x,int y) {
  switch(button) {
  case GLUT_LEFT_BUTTON:
    {
      leftHeld = state == GLUT_DOWN;
      if(leftHeld)
      {
        points.push_back(convertToNdc(x,y)); // add new point
      }
      else
        points.back() = convertToNdc(x,y); // update last point
    }
    break;

  // on right click,empty the array
  // (but only if the left mouse button isn't currently pressed!)
  case GLUT_RIGHT_BUTTON: 
    if(!leftHeld && state == GLUT_DOWN)
      points.clear();
    break;
  }
  glutPostRedisplay();
}

最后,如果要在单击并在屏幕上拖动时看到线条更新,则需要注册一个鼠标移动功能来更新数组中的最后一个点

// register with glutMotionFunc. 
// code updates last coordinate whilst mouse is moving,and
// the left button is held. 
void onMouseMove(int x,int y) {
  if(leftHeld)
  {
    points.back() = convertToNdc(x,y);
  }
  glutPostRedisplay();
}
本文链接:https://www.f2er.com/3148336.html

大家都在问