我是 OpenGL 和 C++ 的新手,但我有一些 C、Java 和 Python 的背景。
我正在打乒乓球,但屏幕上没有绘制我的 Ball 对象。有什么我没看到的吗?
我的猜测是它是主要方法中的一些东西,或者只是我忽略的东西,但我在它上面花了一点时间,但似乎没有任何效果。
#include <GL/glut.h>
#include <cmath>
class GameObject
{
public:
float xpos;
float ypos;
void draw() {}
void update() {}
};
class Paddle : public GameObject
{
public:
float xlen;
float ylen;
float xvel;
float yvel;
Paddle() {}
Paddle(float x, float y, float xl, float yl, float xv, float yv)
{
xpos = x;
ypos = y;
xlen = xl;
ylen = yl;
xvel = xv;
yvel = yv;
}
void draw()
{
glPushMatrix();
glTranslatef(xpos, ypos, 0.0f);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
glVertex2f(-xlen, -ylen);
glVertex2f(-xlen, ylen);
glVertex2f(xlen, ylen);
glVertex2f(xlen, -ylen);
glEnd();
glPopMatrix();
}
void update()
{
xpos += xvel;
ypos += yvel;
if (xpos > 1.0f || xpos < -1.0f)
{
xvel *= -1.0f;
}
if (ypos > 1.0f || ypos < -1.0f)
{
yvel *= -1.0f;
}
}
};
class Ball : public GameObject
{
public:
float rad;
float xvel;
float yvel;
Ball() {}
Ball(float x, float y, float rad, float xv, float yv)
{
xpos = x;
ypos = y;
rad = rad;
xvel = xv;
yvel = yv;
}
void draw()
{
glPushMatrix();
glTranslatef(xpos, ypos, 0.0f);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLE_FAN);
for (int i = 0; i < 360; i++)
{
float theta = i * 3.14159 / 180;
glVertex2f(rad * cos(theta), rad * sin(theta));
}
glEnd();
glPopMatrix();
}
void update()
{
xpos += xvel;
ypos += yvel;
// Check for collision with the edges of the window
if (xpos > 1.0f || xpos < -1.0f)
{
xvel *= -1.0f;
}
if (ypos > 1.0f || ypos < -1.0f)
{
yvel *= -1.0f;
}
}
};
class Game
{
public:
Paddle paddle1;
Paddle paddle2;
Ball ball;
Game()
: paddle1(-0.85f, 0.0f, 0.05f, 0.3f, 0.0f, 0.1f),
paddle2(0.85f, 0.0f, 0.05f, 0.3f, 0.0f, -0.1f),
ball(0.0f, 0.0f, 0.3f, 0.0f, 0.0f)
{
}
};
Game game = Game(); // global game object
void display()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT);
// Draw the paddles
game.paddle1.draw();
game.paddle2.draw();
// Draw the ball
game.ball.draw();
// Swap the front and back buffers (double buffering)
glutSwapBuffers();
}
void update(int value)
{
// Update the object's position
game.paddle1.update();
game.paddle2.update();
game.ball.update();
// Redraw the scene
glutPostRedisplay();
// Call update() again after 16 milliseconds (60 frames per second)
glutTimerFunc(16, update, 0);
}
int main(int argc, char **argv)
{
// Initialize GLUT and create the window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(720, 720);
glutCreateWindow("Pong");
// Set up the display and update callbacks
glutDisplayFunc(display);
glutTimerFunc(0, update, 0);
// Start the main loop
glutMainLoop();
return 0;
}
我试过弄乱它,甚至给它相同的代码来绘制桨,但它不起作用。