Opengl台球数组

opengl array of pool balls

本文关键字:数组 Opengl      更新时间:2023-10-16

我正在使用c++在opengl中绘制一个台球数组我面临的问题是数组画在一条直线上。当我使用gltranslate时,当我编辑z轴和y轴时,球仍然只能沿着直线移动我想做的是把球摆成一个三角形,就像台球比赛结束一样我如何使用数组代码来设置像这样的球?如有任何帮助,不胜感激

 balls[7];
    for (int x = ball-start; x<ball-end;x++)
    {
       glTranslatef(0,0,0.5);
       glColor3f(1,0,0);
       ball[x].drawball();
    }

假设:

struct Ball {
    double x,y,z;
    void drawball(void);
    /* ... */
    } ball[7];

试题:

for(int i=0; i<7 ;i++)
    {
    glPushMatrix();
        glTranslated(ball[i].x,ball[i].y,ball[i].z);
        glColor3f(1,0,0);
        ball[i].drawball();
    glPopMatrix();
    }

细节可能有所不同,但希望您能理解。

这样做:

// first of all, include the x,y position (assuming 2D, since pool) in the Ball object:
class Ball
{
   //...
   private:
      float xpos, ypos;
   //...
};

然后,当你构建球数组时,而不是仅仅制作8个球,你会想要在堆上分配内存,以便它可以在整个游戏中持续使用。所以这样做:

Ball *ball= new Ball*[8];
ball[0] = new Ball(x0,y0);
ball[1] = new Ball(x1,y1);
ball[2] = new Ball(x2,y2);
ball[3] = new Ball(x3,y3);
// ...

确保当你的游戏结束时,你自己清理。

for (int i = 0; i < 8; i++)
   delete ball[i];
delete [] ball;

然后在你的Ball::draw()中做这样的事情:

Ball::draw() 
{
   glColor3f(/*yellow*/); // Set the color to yellow 
   glTranslatef(-xpos, -ypos, 0); // Move to the position of the ball
   // Draw the ball
   glTranslatef(xpos, ypos, 0); // Move back to the default position
}

你所要做的就是找出正确的(x0,y0),(x1,y1),(x2,y2)…形成一个三角形!这样回答你的问题了吗?