forked from Manan07Ag/LogicLabs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpinball.cpp
107 lines (87 loc) · 2.43 KB
/
pinball.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <GL/glut.h>
// Ball properties
float ballX = 0.0f;
float ballY = 0.0f;
float ballRadius = 0.05f;
float ballSpeedX = 0.02f;
float ballSpeedY = 0.02f;
// Bar properties
float barX = 0.0f;
float barWidth = 0.4f;
float barHeight = 0.02f;
// Window dimensions
int windowWidth = 800;
int windowHeight = 600;
void init() {
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
void drawBall() {
glLoadIdentity();
glTranslatef(ballX, ballY, 0.0);
glColor3f(1.0, 0.0, 0.0); // Red ball
glBegin(GL_TRIANGLE_FAN);
for (float angle = 0.0; angle <= 2.0 * 3.141592; angle += 0.01) {
float x = ballRadius * cos(angle);
float y = ballRadius * sin(angle);
glVertex2f(x, y);
}
glEnd();
}
void drawBar() {
glLoadIdentity();
glTranslatef(barX, -0.9, 0.0);
glColor3f(0.0, 0.0, 1.0); // Blue bar
glBegin(GL_QUADS);
glVertex2f(-barWidth / 2, 0.0);
glVertex2f(barWidth / 2, 0.0);
glVertex2f(barWidth / 2, barHeight);
glVertex2f(-barWidth / 2, barHeight);
glEnd();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
// Update ball position
ballX += ballSpeedX;
ballY += ballSpeedY;
// Ball collisions with walls
if (ballX + ballRadius > 1.0 || ballX - ballRadius < -1.0) {
ballSpeedX = -ballSpeedX;
}
if (ballY + ballRadius > 1.0 || ballY - ballRadius < -1.0) {
ballSpeedY = -ballSpeedY;
}
// Ball collision with bar
if (ballY - ballRadius < -0.9 && ballX >= barX - barWidth / 2 && ballX <= barX + barWidth / 2) {
ballSpeedY = -ballSpeedY;
}
drawBall();
drawBar();
glutSwapBuffers();
}
void mouseMotion(int x, int y) {
// Convert mouse coordinates to OpenGL coordinates
barX = (x / static_cast<float>(windowWidth) * 2.0) - 1.0;
// Ensure the bar stays within the window boundaries
if (barX - barWidth / 2 < -1.0) {
barX = -1.0 + barWidth / 2;
}
else if (barX + barWidth / 2 > 1.0) {
barX = 1.0 - barWidth / 2;
}
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Ball and Bar");
init();
glutDisplayFunc(display);
glutPassiveMotionFunc(mouseMotion);
glutMainLoop();
return 0;
}