I've written a simple brick breaker game in OpenGL. The ball is a 2D circle drawn using :
for (float angle = 0; angle < (10); angle+=0.01)
{
glVertex2f((x_pos + sin(angle) * RADIUS), (y_pos + (cos(angle)) * RADIUS));
}
This causes distortion when the game is changed to fullscreen. RADIUS is defined as 0.025 .
I need help in making the paddle movements smooth as well.
Also, if you play the game a couple of times, you'll notice that towards the extreme left, when the ball hits the paddle, it rises to a certain height and then bounces back down.
Full code:
#include <GL/openglut.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#define RADIUS 0.025
#define SPEED 0.001
int WIDTH = 900;
int HEIGHT = 650;
int RATIO = WIDTH/HEIGHT;
bool show[5][10];
float x_brick[4][9];
float y_brick[4][9];
float P_XPOS = 0;
float P_YPOS = -0.8;
bool phit_center = false , phit_corner = false;
bool game_over = false;
bool RIGHT = 1,LEFT = 0,UP = 1,DOWN = 0;
bool started = false;
float x_pos = 0,y_pos = -0.75;
bool hit = false;
int lives = 3;
using namespace std;
void b_draw()
{
glColor3f(1.0,0.0,0.0);
glBegin(GL_QUADS);
for(int a = 0; a < 9; a++)
{
for(int b = 0; b < 4; b++)
{
if(show[b][a] == 1)
{
glVertex2f(x_brick[b][a],y_brick[b][a]);
glVertex2f(x_brick[b][a],y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a]+0.2,y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a]+0.2,y_brick[b][a]);
}
}
}
glEnd();
}
void c_draw()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x_pos,y_pos);
for (float angle = 0; angle < (10); angle+=0.01)
{
glVertex2f((x_pos + sin(angle) * RADIUS), (y_pos + (cos(angle)) * RADIUS));
}
glEnd();
}
bool b_hit()
{
hit = false;
int flag = 1;
for(int a = 0; a < 10; a++)
{
for(int b =0; b < 4; b++)
{
if(x_pos >= x_brick[b][a] && x_pos <= x_brick[b][a] + 0.2)
{
if(y_pos <= y_brick[b][a] && y_pos >= y_brick[b][a] - 0.1)
{
if(show[b][a] == 1)
{
show[b][a] = 0;
flag = 0;
hit = true;
break;
}
}
}
}
if(flag == 0)
break;
}
return hit;
}
bool crashed()
{
if(y_pos < P_YPOS - 0.05)
return true;
else return false;;
}
void p_hit()
{
phit_corner = false;
phit_center = false;
if(x_pos <= P_XPOS + 0.13 && x_pos >= P_XPOS - 0.13)
{
if(y_pos <= P_YPOS)
{
phit_center = true;
}
}
else if((x_pos >= P_XPOS + 0.13 && x_pos <= P_XPOS + 0.2) || (x_pos <= P_XPOS - 0.13 && x_pos >= P_XPOS - 0.2))
{
if(y_pos <= P_YPOS)
{
phit_corner = true;
}
}
}
void c_move()
{
if(UP && RIGHT)
{
x_pos += (SPEED);
y_pos += (SPEED);
}
if(UP && LEFT)
{
x_pos -= (SPEED);
y_pos += (SPEED);
}
if(DOWN && RIGHT)
{
x_pos += (SPEED);
y_pos -= (SPEED);
}
if(DOWN && LEFT)
{
x_pos -= (SPEED);
y_pos -= (SPEED);
}
b_hit();
if(x_pos >= (RATIO-RADIUS))
{
RIGHT = 0;
LEFT = 1;
}
else if(x_pos <= (-RATIO+RADIUS))
{
RIGHT = 1;
LEFT = 0;
}
if(y_pos >= (RATIO-RADIUS) || hit )
{
UP = 0;
DOWN = 1;
}
else if(y_pos <= (-RATIO+RADIUS) || hit )
{
UP = 1;
DOWN = 0;
}
p_hit();
if(phit_center)
{
DOWN = 0;
UP = 1;
}
if(phit_corner)
{
if(LEFT)
{
LEFT = 0;
RIGHT = 1;
}
else
{
RIGHT = 0;
LEFT = 1;
}
UP = 1;
DOWN = 0;
}
}
void p_draw()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_QUADS);
glVertex2f(P_XPOS-0.2,P_YPOS);
glVertex2f(P_XPOS+0.2,P_YPOS);
glVertex2f(P_XPOS+0.2,P_YPOS-0.05);
glVertex2f(P_XPOS-0.2,P_YPOS-0.05);
glEnd();
}
void BallLoop()
{
glClearColor(1.0,1.0,1.0,0);
glDisable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
c_draw();
b_draw();
p_draw();
glFlush();
if(started)
c_move();
if(crashed())
{
x_pos = 0;
y_pos = -0.7;
started = 0;
UP = 1;
RIGHT = 1;
DOWN = 0;
LEFT = 0;
}
glutSwapBuffers();
glutPostRedisplay();
}
void user_input(unsigned char key, int x, int y)
{
if(key == 13)
started = true;
}
void ArrowKeys(int key, int x, int y)
{
if(key==GLUT_KEY_LEFT && P_XPOS >= -0.8)
for(float a = 0; a < 0.05; a+= 0.001)
{
P_XPOS -=0.003;
BallLoop();
}
if(key==GLUT_KEY_RIGHT && P_XPOS <= 0.8)
{
for(float a = 0; a < 0.05; a+= 0.001)
{
P_XPOS +=0.003;
BallLoop();
}
}
}
void set_xy()
{
for(int a = 0; a < 5; a++)
{
for(int b = 0; b < 10; b++)
{
show[a][b] = 1;
}
}
int c = 0;
for(float a = -0.94; c <= 8; a+=0.21)
{
for(int b = 0; b <= 5; b++)
{
x_brick[b][c] = a;
}
c++;
}
int d = 0;
for(float s = 0.99; d <= 3; s-=0.11)
{
for(int r = 0; r < 9; r++)
{
y_brick[d][r] = s;
}
d++;
}
}
void changeSize(int w, int h)
{
if(h == 0)
h = 1;
RATIO = w/h;
float ratio = 1.0* w / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
glMatrixMode(GL_MODELVIEW);
BallLoop();
}
int main(int argc, char **argv)
{
set_xy();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(0,0);
glutInitWindowSize(WIDTH,HEIGHT);
glutCreateWindow("Brick Breaker - By Viraj");
glutReshapeFunc(changeSize);
glutDisplayFunc(BallLoop);
glutKeyboardFunc(user_input);
glutSpecialFunc(ArrowKeys);
glutMainLoop();
return 0;
}
A lot of people run into this kind of issue, because they base their code on badly written tutorials. One key mistake is to do the projection matrix setup in the reshape handler. In any serious OpenGL application, games including, you will switch the projection several times during rendering – for HUDs, minimaps, GUI elements etc.
Instead you set projection in the display handler, right before you need that projection. Also you missed to set the projection matrix at all, you only set the viewport - close, but not enough. I'd not call the display handler Ball_Loop, but well, here's how I'd modify it:
void BallLoop()
{
const int win_width = glutGet(GLUT_WINDOW_WIDTH);
const int win_height = glutGet(GLUT_WINDOW_HEIGHT);
const float win_aspect = (float)win_width/(float)win_height;
glClearColor(1.0,1.0,1.0,0);
glDisable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, win_width, win_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-aspect, aspect, -1, 1, -1, 1); /* those ortho limits should match your game logic */
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
c_draw();
b_draw();
p_draw();
glFlush();
if(started)
c_move();
if(crashed())
{
x_pos = 0;
y_pos = -0.7;
started = 0;
UP = 1;
RIGHT = 1;
DOWN = 0;
LEFT = 0;
}
glutSwapBuffers();
glutPostRedisplay();
}
EDIT fully fixed and playable brickbreaker.cc source code
#include <GL/glut.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
#define RADIUS 0.025
#define RATIO (4./3.)
bool show[5][10];
float x_brick[4][9];
float y_brick[4][9];
float paddle_x = 0;
float paddle_y = -0.8;
float paddle_speed = 0;
const float PaddleSpeedFactor = 3.;
bool phit_center = false , phit_corner = false;
bool game_over = false;
float speed_x = 0.;
float speed_y = 0.;
float x_pos = 0,y_pos = -0.75;
int lives = 3;
float T_last_frame = 0.;
void draw_bricks()
{
glColor3f(1.0,0.0,0.0);
glBegin(GL_QUADS);
for(int a = 0; a < 9; a++)
{
for(int b = 0; b < 4; b++)
{
if(show[b][a] == 1)
{
glVertex2f(x_brick[b][a],y_brick[b][a]);
glVertex2f(x_brick[b][a],y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a]+0.2,y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a]+0.2,y_brick[b][a]);
}
}
}
glEnd();
}
void ball_draw()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x_pos,y_pos);
for (float angle = 0; angle < (10); angle+=0.01)
{
glVertex2f((x_pos + sin(angle) * RADIUS), (y_pos + (cos(angle)) * RADIUS));
}
glEnd();
}
bool brick_hit()
{
bool hit = false;
int flag = 1;
for(int a = 0; a < 10; a++)
{
for(int b =0; b < 4; b++)
{
if(x_pos >= x_brick[b][a] && x_pos <= x_brick[b][a] + 0.2)
{
if(y_pos <= y_brick[b][a] && y_pos >= y_brick[b][a] - 0.1)
{
if(show[b][a] == 1)
{
show[b][a] = 0;
flag = 0;
hit = true;
break;
}
}
}
}
if(flag == 0)
break;
}
return hit;
}
bool crashed()
{
if(y_pos < paddle_y - 0.05)
return true;
return false;
}
void paddle_hit()
{
phit_corner = false;
phit_center = false;
if(x_pos <= paddle_x + 0.13 && x_pos >= paddle_x - 0.13)
{
if(y_pos <= paddle_y)
{
phit_center = true;
}
}
else if( (x_pos >= paddle_x + 0.13 && x_pos <= paddle_x + 0.2) ||
(x_pos <= paddle_x - 0.13 && x_pos >= paddle_x - 0.2))
{
if(y_pos <= paddle_y)
{
phit_corner = true;
}
}
}
void paddle_move(float dT)
{
if(paddle_x < RATIO && paddle_x > -RATIO)
paddle_x += paddle_speed * PaddleSpeedFactor * dT;
if( paddle_x > 0.95) {
paddle_x = 0.95;
paddle_speed = 0.;
}
if( paddle_x < -0.95) {
paddle_x = -0.95;
paddle_speed = 0.;
}
paddle_speed *= (1. - 0.05);
if( fabs(paddle_speed) < 0.01 )
paddle_speed = 0.;
}
void ball_move(float dT)
{
x_pos += speed_x * dT;
y_pos += speed_y * dT;
if( brick_hit() ) {
speed_y *= -1;
}
if( x_pos >= (RATIO-RADIUS) || x_pos <= (-RATIO+RADIUS ) )
{
speed_x *= -1;
}
if( y_pos >= (1.-RADIUS) )
{
speed_y = -1;
}
paddle_hit();
if(phit_center)
{
speed_y = 1;
}
if(phit_corner)
{
speed_x *= -1;
speed_y = 1;
}
}
void paddle_draw()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_QUADS);
glVertex2f(paddle_x - 0.2, paddle_y);
glVertex2f(paddle_x + 0.2, paddle_y);
glVertex2f(paddle_x + 0.2, paddle_y - 0.05);
glVertex2f(paddle_x - 0.2, paddle_y - 0.05);
glEnd();
}
void step_game()
{
paddle_move(T_last_frame);
ball_move(T_last_frame);
if(crashed())
{
speed_x = 0;
speed_y = 0;
x_pos = 0;
y_pos = -0.7;
paddle_speed = 0;
paddle_x = 0;
}
glutPostRedisplay();
}
void launch_ball()
{
speed_y = 1.;
speed_x = 1.;
}
void user_input(unsigned char key, int x, int y)
{
if(key == 13)
launch_ball();
}
void ArrowKeys(int key, int x, int y)
{
if(key==GLUT_KEY_LEFT)
paddle_speed = -1.;
if(key==GLUT_KEY_RIGHT)
paddle_speed = +1.;
}
void set_xy()
{
for(int a = 0; a < 5; a++)
{
for(int b = 0; b < 10; b++)
{
show[a][b] = 1;
}
}
int c = 0;
for(float a = -0.94; c <= 8; a+=0.21)
{
for(int b = 0; b <= 5; b++)
{
x_brick[b][c] = a;
}
c++;
}
int d = 0;
for(float s = 0.99; d <= 3; s-=0.11)
{
for(int r = 0; r < 9; r++)
{
y_brick[d][r] = s;
}
d++;
}
}
void display()
{
const int win_width = glutGet(GLUT_WINDOW_WIDTH);
const int win_height = glutGet(GLUT_WINDOW_HEIGHT);
const float win_aspect = (float)win_width / (float)win_height;
glViewport(0, 0, win_width, win_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(win_aspect > RATIO) {
glOrtho(-win_aspect, win_aspect, -1., 1., -1., 1.);
} else {
glOrtho(-RATIO, RATIO, -RATIO/win_aspect, RATIO/win_aspect, -1., 1.);
}
glMatrixMode(GL_MODELVIEW);
glClearColor(0., 0., 1., 1.);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(1,1,1);
glVertex2f(-RATIO, -1);
glVertex2f(RATIO, -1);
glVertex2f(RATIO, 1);
glVertex2f(-RATIO, 1);
glEnd();
draw_bricks();
paddle_draw();
ball_draw();
glutSwapBuffers();
// GLUT doesn't offer cross plattform timing
// assume 60Hz refresh rate
T_last_frame = 1./60.;
}
int main(int argc, char **argv)
{
set_xy();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(0,0);
glutInitWindowSize(800, 600);
glutCreateWindow("Brick Breaker - By Viraj");
glutDisplayFunc(display);
glutKeyboardFunc(user_input);
glutSpecialFunc(ArrowKeys);
glutIdleFunc(step_game);
glutMainLoop();
return 0;
}
EDIT 2 and just for the sake of completeness, here's a GLFW version
#include <GL/glfw.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
#define RADIUS 0.025
#define RATIO (4./3.)
bool show[5][10];
float x_brick[4][9];
float y_brick[4][9];
const float SpeedFactor = 10.;
float paddle_x = 0;
float paddle_y = -0.8;
float paddle_speed = 0;
const float PaddleSpeedFactor = 3.;
bool phit_center = false, phit_corner = false;
bool game_over = false;
float speed_x = 0.;
float speed_y = 0.;
float x_pos;
float y_pos;
int lifes = 0;
void draw_bricks()
{
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_QUADS);
for (int a = 0; a < 9; a++) {
for (int b = 0; b < 4; b++) {
if (show[b][a] == 1) {
glVertex2f(x_brick[b][a], y_brick[b][a]);
glVertex2f(x_brick[b][a], y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a] + 0.2,
y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a] + 0.2, y_brick[b][a]);
}
}
}
glEnd();
}
void ball_draw()
{
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x_pos, y_pos);
for (float angle = 0; angle < (10); angle += 0.01) {
glVertex2f((x_pos + sin(angle) * RADIUS),
(y_pos + (cos(angle)) * RADIUS));
}
glEnd();
}
bool brick_hit()
{
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 4; b++) {
if (x_pos >= x_brick[b][a]
&& x_pos <= x_brick[b][a] + 0.2) {
if (y_pos <= y_brick[b][a]
&& y_pos >= y_brick[b][a] - 0.1) {
if (show[b][a] == 1) {
show[b][a] = 0;
return true;
}
}
}
}
}
return false;
}
bool crashed()
{
if (y_pos < paddle_y - 0.05)
return true;
return false;
}
void paddle_hit()
{
phit_corner = false;
phit_center = false;
if (x_pos <= paddle_x + 0.13 && x_pos >= paddle_x - 0.13) {
if (y_pos <= paddle_y) {
phit_center = true;
}
} else if ((x_pos >= paddle_x + 0.13 && x_pos <= paddle_x + 0.2) ||
(x_pos <= paddle_x - 0.13 && x_pos >= paddle_x - 0.2)) {
if (y_pos <= paddle_y) {
phit_corner = true;
}
}
}
void paddle_move(float dT)
{
if (paddle_x < RATIO && paddle_x > -RATIO)
paddle_x += paddle_speed * PaddleSpeedFactor * dT;
if (paddle_x > 1.) {
paddle_x = 1.;
paddle_speed = 0.;
}
if (paddle_x < -1.) {
paddle_x = -1.;
paddle_speed = 0.;
}
}
void ball_move(float dT)
{
x_pos += speed_x * dT;
y_pos += speed_y * dT;
if (brick_hit()) {
speed_y *= -1;
}
if (x_pos >= (RATIO - RADIUS) || x_pos <= (-RATIO + RADIUS)) {
speed_x *= -1;
}
if (y_pos >= (1. - RADIUS)) {
speed_y = -1;
}
paddle_hit();
if (phit_center) {
speed_y = 1;
}
if (phit_corner) {
speed_x *= -1;
speed_y = 1;
}
}
void paddle_draw()
{
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_QUADS);
glVertex2f(paddle_x - 0.2, paddle_y);
glVertex2f(paddle_x + 0.2, paddle_y);
glVertex2f(paddle_x + 0.2, paddle_y - 0.05);
glVertex2f(paddle_x - 0.2, paddle_y - 0.05);
glEnd();
}
void reset_game()
{
lifes = 3;
speed_x = 0;
speed_y = 0;
x_pos = 0;
y_pos = -0.7;
paddle_speed = 0;
paddle_x = 0;
}
void step_game(float dT)
{
if(!lifes)
return;
paddle_move(dT * SpeedFactor);
ball_move(dT * SpeedFactor);
if (crashed()) {
lifes--;
speed_x = 0;
speed_y = 0;
x_pos = 0;
y_pos = -0.7;
}
}
void launch_ball()
{
if(!lifes)
return;
speed_y = 1.;
speed_x = 1.;
}
void keyboard(int key, int action)
{
switch(key)
{
case GLFW_KEY_ENTER:
launch_ball();
break;
case GLFW_KEY_ESC:
reset_game();
break;
case GLFW_KEY_LEFT:
switch(action) {
case GLFW_PRESS:
paddle_speed = -1.;
break;
case GLFW_RELEASE:
paddle_speed = 0;
break;
} break;
case GLFW_KEY_RIGHT:
switch(action) {
case GLFW_PRESS:
paddle_speed = 1.;
break;
case GLFW_RELEASE:
paddle_speed = 0;
break;
} break;
}
}
void set_xy()
{
for (int a = 0; a < 5; a++) {
for (int b = 0; b < 10; b++) {
show[a][b] = 1;
}
}
int c = 0;
for (float a = -0.94; c <= 8; a += 0.21) {
for (int b = 0; b <= 5; b++) {
x_brick[b][c] = a;
}
c++;
}
int d = 0;
for (float s = 0.99; d <= 3; s -= 0.11) {
for (int r = 0; r < 9; r++) {
y_brick[d][r] = s;
}
d++;
}
}
float display()
{
int win_width;
int win_height;
glfwGetWindowSize(&win_width, &win_height);
const float win_aspect = (float)win_width / (float)win_height;
glfwSetTime(0.);
glViewport(0, 0, win_width, win_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (win_aspect > RATIO) {
glOrtho(-win_aspect, win_aspect, -1., 1., -1., 1.);
} else {
glOrtho(-RATIO, RATIO, -RATIO / win_aspect, RATIO / win_aspect,
-1., 1.);
}
glMatrixMode(GL_MODELVIEW);
glClearColor(0., 0., 1., 1.);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
glVertex2f(-RATIO, -1);
glVertex2f(RATIO, -1);
glVertex2f(RATIO, 1);
glVertex2f(-RATIO, 1);
glEnd();
draw_bricks();
paddle_draw();
ball_draw();
glfwSwapBuffers();
return glfwGetTime();
}
int main(int argc, char **argv)
{
set_xy();
if( GL_FALSE == glfwInit() )
return -1;
if( GL_FALSE == glfwOpenWindow(800, 600, 8, 8, 8, 8, 0, 0, GLFW_WINDOW) )
return -2;
glfwSetWindowTitle("Viraj's Brick Breaker - GLFW version by datenwolf");
glfwSetKeyCallback(keyboard);
reset_game();
while( glfwGetWindowParam(GLFW_OPENED) ) {
glfwPollEvents();
float const dT = display();
step_game(dT);
}
glfwTerminate();
return 0;
}
i think your distortion is due to your changeSize(...) function: you calculate the aspect ratio of of your window, but you do not use it. Have a look at the code where you stole this snippet from :)
Do you change resolution of your screen when switching to fullscreen mode? If you do, it is very likely that a pixel is not square anymore, so you will need the actual aspect ratio of your screen.
Related
I have a simple 2D simulation which has particles travelling at given velocities and could collide with each other and the walls. But the fps drops when there are more than 500 particles. I want to simulate at least 5000 particles smoothly because I'll be adding more features to the program. Is there a different and efficient approach to this? Thanks!
gas.cpp:
#include<cstdlib>
#include<vector>
#include<glut.h>
#include "gas.h"
#include<time.h>
float t = 1; //time step
void gas::p(float pos_x, float pos_y, float vx, float vy, float mass)
{
srand(time(0));
m = mass;
x = pos_x;
y = pos_y;
velx = vx;
vely = vy;
size = 3;
}
void gas::draw()
{
glColor3f(1, 1, 1);
glVertex2f(x, y);
}
void gas::move(float t)
{
x += velx * t;
y += vely * t;
}
float temp;
//Function to be ran at every frame:
void run(std::vector <gas>& bn)
{
int it = 0;
for (gas& i : bn)
{
int jt = 0;
for (gas& j : bn)
{
if (it != jt)
{
//Handling collisions:
if (abs(i.y - (j.y + j.size)) < 1 && (abs(j.x - i.x) <= i.size + 1) && i.vely < 0)
{
temp = i.vely;
i.vely = j.vely;
j.vely = temp;
}
if (abs(j.y - (i.y + i.size)) < 1 && (abs(i.x - j.x) <= j.size + 1) && i.vely > 0)
{
temp = i.vely;
i.vely = j.vely;
j.vely = temp;
}
if (abs(j.x - (i.x + i.size)) < 1 && (abs(i.y - j.y) <= i.size + 1) && i.velx > 0)
{
temp = i.velx;
i.velx = j.velx;
j.velx = temp;
}
if (abs(i.x - (j.x + j.size)) < 1 && (abs(j.y - i.y) <= i.size + 1) && i.velx < 0)
{
temp = i.velx;
i.velx = j.velx;
j.velx = temp;
}
}
jt += 1;
}
//Boundary Collisions:
if (i.x > 600 - i.size) { i.x = 600 - i.size; i.velx = -i.velx; }
if (i.x < i.size) { i.x = i.size; i.velx = -i.velx; }
if (i.y > 600 - i.size) { i.y = 600 - i.size; i.vely = -i.vely; }
if (i.y < i.size) { i.y = i.size; i.vely = -i.vely; }
i.move(t);
it += 1;
}
}
gas.h:
#pragma once
class gas
{
public:
float m = 1;
float x = 0;
float y = 0;
float velx = 0;
float vely = 0;
float size = 3;
float density = 100;
float r = 1; float g = 1; float b = 1;
void p(float pos_x, float pos_y, float vx, float vy, float mass);
void draw();
void move(float t);
};
void run(std::vector<gas>& bn);
simulate.cpp (main file):
#include<cstdlib>
#include<glut.h>
#include<vector>
#include "gas.h"
#include<thread>
#include<time.h>
void display();
void reshape(int, int);
const int n = 600; //Number of particles
void init()
{
glClearColor(0, 0, 0, 1);
}
std::vector <gas> b(n);
void timer(int)
{
run(b);
glutPostRedisplay();
glutTimerFunc(1000 / 60, timer, 0);
}
void show(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(300, 60);
glutInitWindowSize(600, 600);
glutCreateWindow("Particles");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutTimerFunc(1000, timer, 0); // Args: Time delay per frame in milliseconds, function to be called
init();
glutMainLoop();
}
int main(int argc, char** argv)
{
int it = 0;
for (gas& i : b)
{
srand(it);
i.p(rand() % 600, rand() % 600, (rand() % 10) * pow(-1, it + 1), (rand() % 10) * pow(-1, it), 1);
it += 1;
}
show(argc, argv);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glPointSize(3);
glBegin(GL_POINTS);
for (gas& i : b)
{
i.draw();
}
glEnd();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 600, 0, 600);
glMatrixMode(GL_MODELVIEW);
}
I'm trying to make Bezier curve by control point.
I have some examples and followed it. But it did not work.
It shows the line is going to (0, 0) points during working.
I still don't get it why.
Here's the code in the C++ language, using OpenGL.
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <gl/glut.h>
#include <gl/GLU.h>
#include <gl/GL.h>
#include <math.h>
#define CTRL_COUNT 100
void display();
void init();
float getNextBezierPointX(float t);
float getNextBezierPointY(float t);
void drawline();
int ctrlPointsCount;
int ctrlPointsX[CTRL_COUNT], ctrlPointsY[CTRL_COUNT];
int X1[20] = { 10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105 };
int Y1[20] = { 50,60,40,70,40,60,35,80,45,55,30,60,40,60,40,55,35,70,40,50 };
void main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(500, 300);
glutCreateWindow("Bezier");
glutDisplayFunc(display);
init();
glutMainLoop();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
ctrlPointsCount = 20;
for (int i = 0; i < 20; i++) {
ctrlPointsX[i] = X1[i];
ctrlPointsY[i] = Y1[i];
}
drawline();
glFlush();
}
void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glPointSize(8.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 128.0, 0.0, 96.0);
}
float getNextBezierPointX(float t) {
float x = 0.0;
int c;
for (int i = 0; i < ctrlPointsCount; i ++) {
if (i == 0 || i == ctrlPointsCount - 1)
c = 1;
else
c = ctrlPointsCount - 1;
x = x + c * pow(t, i) * pow(1 - t, ctrlPointsCount - 1 - i) * ctrlPointsX[i];
}
return x;
}
float getNextBezierPointY(float t) {
float y = 0.0;
int c;
for (int i = 0; i < ctrlPointsCount; i ++) {
if (i == 0 || i == ctrlPointsCount - 1)
c = 1;
else
c = ctrlPointsCount - 1;
y = y + c * pow(t, i) * pow(1 - t, ctrlPointsCount - 1 - i) * ctrlPointsY[i];
}
return y;
}
void drawline() {
float x, y;
for (int i = 0; i < 20; i++) {
glBegin(GL_POINTS);
glVertex2i(ctrlPointsX[i], ctrlPointsY[i]);
glEnd();
glFlush();
}
float oldX = ctrlPointsX[0], oldY = ctrlPointsY[0];
for (double t = 0.0; t <= 1.0; t += 0.01) {
x = getNextBezierPointX(t);
y = getNextBezierPointY(t);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
glVertex2f(oldX, oldY);
glVertex2f(x, y);
glEnd();
glFlush();
oldX = x;
oldY = y;
}
}
For a bezier curve like this you have to calculate Bernstein polynomials:
double factorial(int n)
{
double x = 1.0;
for (int i = 1; i <= n; i++)
x *= (double)i;
return x;
}
double Ni(int n, int i)
{
double a1 = factorial(n);
double a2 = factorial(i);
double a3 = factorial(n - i);
double ni = a1/ (a2 * a3);
return ni;
}
double Bernstein(int n, int i, double t)
{
double ti = (t == 0.0 && i == 0) ? 1.0 : pow(t, i); /* t^i */
double tni = (n == i && t == 1.0) ? 1.0 : pow((1 - t), (n - i)); /* (1 - t)^i */
double basis = Ni(n, i) * ti * tni; //Bernstein basis
return basis;
}
The code to create the curve may look like this:
struct vec2
{
double x, y;
};
vec2 getBezierPoint(float t, int n, int x[], int y[] )
{
vec2 pt{ 0.0, 0.0 };
for (int i = 0; i < n; i ++) {
double b = Bernstein( n - 1, i, t );
pt.x += b * x[i];
pt.y += b * y[i];
}
return pt;
}
float oldX = ctrlPointsX[0], oldY = ctrlPointsY[0];
for (double t = 0.0; t <= 1.0; t += 0.01)
{
vec2 pt = getBezierPoint( t, ctrlPointsCount, ctrlPointsX, ctrlPointsY );
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
glVertex2f(oldX, oldY);
glVertex2f((float)pt.x, (float)pt.y);
glEnd();
glFlush();
oldX = (float)pt.x; oldY = (float)pt.y;
}
An other solution is provided in the answer to the Stack Overflow question How do I implement a Bézier curve in C++?:
#include <vector>
vec2 getBezierPoint2( float t, int n, int x[], int y[] )
{
std::vector<double> tmpx( n ), tmpy( n );
for ( int i=0; i<n; ++ i )
{
tmpx[i] = x[i];
tmpy[i] = y[i];
}
int i = n - 1;
while (i > 0)
{
for (int k = 0; k < i; k++)
{
tmpx[k] = tmpx[k] + t * ( tmpx[k+1] - tmpx[k] );
tmpy[k] = tmpy[k] + t * ( tmpy[k+1] - tmpy[k] );
}
i--;
}
return { tmpx[0], tmpy[0] };
}
But may be the result is not what you expect it to be, because you create a Higher-order Bézier curve which results in a very flat curve:
Maybe you want to connect any number of points with square bezier curves: Quadratic Bézier Curve: Calculate Points
I have a problem with my opengl project. I have to create moving triangle alonge x-axis. It laso has to change its colour and turn around. I have created this but i don`t know what is going on with acceleration...
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
#include <math.h>
#include<iomanip>
#include <time.h>
#include "glut.h"
#include "math.h"
using namespace std;
float x = 0, y = 0, angle = 0, anglen = 0,q=1,w=1,e=1,qn=0,wn=0,en=0;
double xn = 0,c=0;
int licznik = 0;
int zmiana = 0,a=0;
bool flaga = true;
static void timerCallback(int value)
{
if (xn!=x)
{
licznik++; //odliczanie kolejnych klatek
x += xn / 100.0;
angle += anglen / 100.0;
q += qn / 100.0;
w += wn / 100.0;
e += en / 100.0;
if (q > 1){ q = 0; }
if (w > 1){ w = 0; }
if (e > 1){ e = 0; }
glutPostRedisplay();
glutTimerFunc(50, timerCallback, value); //ustawienie ponownego wywołania naszej funkcji "timerCallback" po 100 ms
}
if (licznik==100)
{
if (a == 0){ x = -0.8; glutPostRedisplay(); }
else if (a == 1){ x = 0; glutPostRedisplay(); }
else if (a == 2){ x = 0.8; glutPostRedisplay(); }
else if (a == 3){ x = 0; glutPostRedisplay(); }
xn = 0;
anglen = 0;
licznik = 0;
zmiana = 1;
}
}
void trojkat(float x, float y, float angle)
{
glColor3f(q, w, e);
glPushMatrix();
glTranslatef(x, y, 0);
glRotatef(angle, 0, 0, 1);
glBegin(GL_POLYGON);
glVertex2f(0, 0.2);
glVertex2f(-0.2, -0.2);
glVertex2f(0.2, -0.2);
glEnd();
glPopMatrix();
}
void przesuwanie()
{
a++;
if (a >3){ a = 0; };
if ((a == 1) || (a == 2)){ flaga = true; }
else if ((a == 0) || (a == 3)){flaga = false;}
if (flaga == true)
{
xn += .8; anglen += 360;
qn += .1;
wn += .7;
en += .3;
}
else if (flaga == false)
{
xn -= .8; anglen += 360;
qn += .8;
wn += .4;
en += .3;
}
zmiana = 4;
//wyzerowanie zliczania klatek
timerCallback(0); //wywołanie funkcji która będzie się okresowo powtarzać
}
void przesuwanie_w_lewo()// pierwsze przesuniecie o połowe jednostki
{
xn = 0;
xn -= .8;
anglen += 360;
qn -= .9;
wn -= .7;
en -= .3;
zmiana = 4;
timerCallback(0);
//wywołanie funkcji która będzie się okresowo powtarzać
}
void display(void)
{
/* clear window */
glClear(GL_COLOR_BUFFER_BIT);
trojkat(x, y, angle);
glFlush();
if ((zmiana == 0) || (zmiana == 1) || (zmiana == 2))
{
if (zmiana == 0)
{
przesuwanie_w_lewo();
}
else if (zmiana==1)
{
przesuwanie();
}
}
}
void init()
{
/* set clear color to black */
glClearColor(0.0, 0.0, 0.0, 0.0);
/* set fill color to white */
/* set up standard orthogonal view with clipping */
/* box as cube of side 2 centered at origin */
/* This is default view and these statement could be removed */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400, 400);
glutInitWindowPosition(0, 0);
glutCreateWindow("trojkat");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
I have a self intersecting polygon that I am trying to fill using the odd-even rule like so :
I use a scan line and when I detect an edge of the polygon I change the fill color. Here's my code so far :
Edited code :
#include<GL/glut.h>
#include<vector>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<limits>
using namespace std;
const int n = 7;
class Point{
public:
int x, y;
Point(){
};
Point(int a, int b){
x = a;
y = b;
};
void set(int a, int b){
x = a;
y = b;
};
};
Point P[n];
int min(int x, int y)
{
if (x <= y) return x;
else return y;
}
int max(int x, int y)
{
if (x >= y) return x;
else return y;
}
Point solve(Point A, Point B, Point C, Point D)
{ //returns the intersection point between line segments [AB] and [CD]
Point rez;
rez.x = -1;
rez.y = -1;
//[AB]
int A1 = B.y - A.y, B1 = A.x - B.x, C1 = (A1 * A.x) + (B1 * A.y);
//[CD]
int A2 = D.y - C.y, B2 = C.x - D.x, C2 = (A2 * C.x) + (B2 * C.y);
int det = A1*B2 - A2*B1;
if (det == 0){
return Point(-1, -1);
}
else
{
rez.x = (B2*C1 - B1*C2) / det;
rez.y = (A1*C2 - A2*C1) / det;
}
if (!(rez.x >= min(A.x, B.x) && rez.x <= max(A.x, B.x) && rez.x >= min(C.x, D.x) && rez.x <= max(C.x, D.x)))
{
rez.x = -1;
rez.y = -1;
}
return rez;
}
bool intComparison(int i, int j) { return (i < j); }
void scanfill()
{
int i, j, color = 1, k; //alb
vector<int> inter[501];
Point T;
for (j = 0; j < 500; j++) //go line by line
{
for (k = 0; k < n - 1; k++) //loop through all the line segments
{
T = solve(Point(0, j), Point(499, j), P[k], P[k + 1]);
if (!(T.x == -1 && T.y == -1))
{
inter[j].push_back(T.x); // save the x coord. of the intersection point between the line and the sweep line when y = j
}
}
T = solve(Point(0, j), Point(499, j), P[n - 1], P[0]);
if (!(T.x == -1 && T.y == -1))
{
inter[j].push_back(T.x);
}
}
for (j = 0; j < 500; j++)
{
sort(inter[j].begin(), inter[j].end(), intComparison);
}
for (j = 0; j < 500; j++)
{
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINES);
for (vector<int>::iterator it = inter[j].begin(); it != inter[j].end(); it++)
{
glVertex2i(*it, j); //draw the actual lines
}
glEnd();
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
P[0] = Point(100, 235);
P[1] = (Point(100, 100));
P[2] = (Point(230, 140));
P[3] = (Point(40, 200));
P[4] = (Point(20, 60));
P[5] = (Point(300, 150));
P[6] = (Point(150, 111));
glBegin(GL_LINE_LOOP);
for (int i = 0; i < n; i++)
{
glVertex2i(P[i].x, P[i].y);
}
glEnd();
scanfill();
glFlush();
}
void init()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 499.0, 0.0, 499.0);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("scanline");
glutDisplayFunc(display);
init();
glutMainLoop();
}
It seems to detect more intersections between the sweep line and the actual lines than it should for some reason.
Result with the above code :
Desired Result :
I managed to solve the problem. Here's the code if anyone else is interested :
#include<GL/glut.h>
#include<vector>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<limits>
using namespace std;
const int n = 7;
class Point{
public:
int x, y;
Point(){
};
Point(int a, int b){
x = a;
y = b;
};
void set(int a, int b){
x = a;
y = b;
};
};
Point P[n];
int min(int x, int y)
{
if (x <= y) return x;
else return y;
}
int max(int x, int y)
{
if (x >= y) return x;
else return y;
}
double solve(int y, Point A, Point B)
{
if (y >= min(A.y, B.y) && y <= max(A.y, B.y))
{
return ((y * B.x) - (y * A.x) - (A.y * B.x) + (A.x * B.y)) / (B.y - A.y);
}
else return -1;
}
bool doubleComparison(double i, double j) { return (i < j); }
bool isVertex(int x, int y)
{
for (int i = 0; i < n; i++)
{
if (P[i].x == x && P[i].y == y) return 1;
}
return 0;
}
void scanfill()
{
int i, j, color = 1, k;
double x;
vector<double> inter[501];
for (j = 0; j < 500; j++)
{
for (k = 0; k < n - 1; k++)
{
x = solve(j, P[k], P[k + 1]);
if (x != -1 && !isVertex(x,j))
{
inter[j].push_back(x);
}
}
x = solve(j, P[n - 1], P[0]);
if (x != -1 && !isVertex(x, j))
{
inter[j].push_back(x);
}
}
for (j = 0; j < 500; j++)
{
sort(inter[j].begin(), inter[j].end(), doubleComparison);
}
for (j = 0; j < 500; j++)
{
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINES);
for (vector<double>::iterator it = inter[j].begin(); it != inter[j].end(); it++)
{
glVertex2d(*it, j);
}
glEnd();
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
P[0] = Point(100, 235);
P[1] = (Point(100, 100));
P[2] = (Point(230, 140));
P[3] = (Point(40, 200));
P[4] = (Point(20, 60));
P[5] = (Point(300, 150));
P[6] = (Point(150, 111));
glBegin(GL_LINE_LOOP);
for (int i = 0; i < n; i++)
{
glVertex2i(P[i].x, P[i].y);
}
glEnd();
scanfill();
glFlush();
}
void init()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 499.0, 0.0, 499.0);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("scanline");
glutDisplayFunc(display);
init();
glutMainLoop();
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I've written a simple brick breaker game using OpenGL and OpenGLUT. Everthing works as it should, except, when a level gets over, the game hangs. Any idea why ?
I tried telling it to reset all parameters, but nothing works. :(
#include <GL/openglut.h>
#include <cmath>
#include <string>
#include <ctime>
#define RADIUS 0.025
#define P_LENGTH 0.3
using namespace std;
int WIDTH = 900,
HEIGHT = 650,
lives = 3,
SCORE = 0,
LEVEL = 2,
BRICK_ROW = 10,
BRICK_COL = 9;
double x_brick[10][10],
y_brick[10][10],
P_XPOS = 0,
P_YPOS = -0.8,
x_pos = 0,
y_pos = -0.75,
win_aspect,
SPEED = 0;
bool show[10][10],
phit_center = false,
phit_corner = false,
game_over = false,
RIGHT = true,
LEFT = false,
UP = true,
DOWN = false,
started = false,
hit = false;
char life = '0';
void user_input(unsigned char key, int x, int y)
{
if(key == 13)
started = true;
}
void b_draw()
{
glBegin(GL_QUADS);
for(int a = 0; a < BRICK_COL; a++)
{
for(int b = 0; b < BRICK_ROW; b++)
{
switch(b)
{
case 0:
glColor3f(1.0,0.0,0.0);
break;
case 1:
glColor3f(1.0,0.9,0.1);
break;
case 2:
glColor3f(0.0,1.0,0.0);
break;
case 3:
glColor3f(0.11,0.56,1.0);
break;
default:
glColor3f(1.0,0.0,0.0);
}
if(show[b][a] == true)
{
glVertex2f(x_brick[b][a]*win_aspect,y_brick[b][a]);
glVertex2f(x_brick[b][a]*win_aspect,(y_brick[b][a] - 0.10));
glVertex2f((x_brick[b][a]+0.2)*win_aspect,(y_brick[b][a] - 0.10));
glVertex2f((x_brick[b][a]+0.2)*win_aspect,y_brick[b][a]);
}
}
}
glColor3f(0.0,0.0,0.0);
glEnd();
}
void Set_Level(int level)
{
int R_Limit = 0;
switch(level)
{
case 1:
for(int a = 0; a < BRICK_ROW; a++)
{
for(int b = 0; b < BRICK_COL; b++)
{
show[a][b] = 1;
}
}
break;
case 2:
for(int a = 0; a < BRICK_ROW/2; a++)
{
for(int b = 0; b < BRICK_COL; b++)
{
if(b >= BRICK_COL/2 - R_Limit && b<=BRICK_COL/2 + R_Limit)
show[a][b] = true;
}
R_Limit++;
}
R_Limit = BRICK_ROW/2;
for(int a = BRICK_ROW/2; a <= BRICK_ROW; a++)
{
for(int b = 0; b <= BRICK_COL; b++)
{
if(b >= BRICK_COL/2 - R_Limit && b <= BRICK_COL/2 + R_Limit)
show[a][b] = true;
}
R_Limit--;
}
break;
case 3:
for(int a = 0; a <= BRICK_COL/2; a++)
{
show[a][a] = true;
}
for(int a = BRICK_COL; a >= BRICK_COL/2; a--)
{
show[BRICK_COL - a - 1][a] = true;
}
break;
}
}
bool all_gone()
{
int local_flag = 0;
for(int a = 0; a < BRICK_COL; a++)
{
for(int b = 0; b < BRICK_ROW; b++)
{
if(show[b][a] == true)
{
return false;
local_flag = 1;
break;
}
if(local_flag)
break;
}
}
return true;
}
void c_draw()
{
glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x_pos,y_pos);
for (float angle = 0; angle < (10); angle+=0.01)
{
glVertex2f((x_pos + sin(angle) * RADIUS), (y_pos + (cos(angle)) * RADIUS));
}
glEnd();
}
bool crashed()
{
if(y_pos < P_YPOS - 0.1)
return true;
else return false;
}
void c_move()
{
if(UP && RIGHT)
{
x_pos += SPEED;
y_pos += SPEED;
}
if(UP && LEFT)
{
x_pos -= SPEED;
y_pos += SPEED;
}
if(DOWN && RIGHT)
{
x_pos += SPEED;
y_pos -= SPEED;
}
if(DOWN && LEFT)
{
x_pos -= SPEED;
y_pos -= SPEED;
}
}
void p_draw()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_QUADS);
glVertex2f(P_XPOS-P_LENGTH, P_YPOS);
glVertex2f(P_XPOS+P_LENGTH, P_YPOS);
glVertex2f(P_XPOS+P_LENGTH, P_YPOS-0.05);
glVertex2f(P_XPOS-P_LENGTH, P_YPOS-0.05);
glEnd();
}
void SET_BRICKS(int level)
{
switch(level)
{
case 1:
BRICK_ROW = 4;
break;
case 2:
BRICK_ROW = 7;
break;
case 3:
BRICK_ROW = 7;
break;
}
}
void BallLoop()
{
const int win_width = glutGet(GLUT_WINDOW_WIDTH),
win_height = glutGet(GLUT_WINDOW_HEIGHT);
win_aspect = (float)win_width/(float)win_height;
glClearColor(1.0, 1.0, 1.0, 0);
glDisable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, win_width, win_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-win_aspect, win_aspect, -1, 1, -1, 1);
c_draw();
b_draw();
p_draw();
life = '0' + lives;
if(started && lives > 0)
c_move();
glFlush();
glutSwapBuffers();
glutPostRedisplay();
}
void GameLogic()
{
if(all_gone())
{
x_pos = 0;
y_pos = -0.7;
LEVEL++;
for(int a = 0; a < BRICK_ROW; a++)
{
for(int b = 0; b <BRICK_COL; b++)
{
show[a][b] = true;
}
}
phit_center = false,
phit_corner = false,
game_over = false,
RIGHT = true,
LEFT = false,
UP = true,
DOWN = false,
started = false,
hit = false;
SET_BRICKS(LEVEL);
Set_Level(LEVEL);
}
if(x_pos >= win_aspect)
{
RIGHT = 0;
LEFT = 1;
}
else if(x_pos <= -win_aspect)
{
RIGHT = 1;
LEFT = 0;
}
if(y_pos >= 1-RADIUS || hit )
{
UP = 0;
DOWN = 1;
}
else if(y_pos <= -1+RADIUS || hit )
{
UP = 1;
DOWN = 0;
}
hit = false;
int flag = 1;
for(int a = 0; a < BRICK_COL; a++)
{
for(int b =0; b < BRICK_ROW; b++)
{
if(x_pos >= x_brick[b][a]*win_aspect && x_pos <= (x_brick[b][a] + 0.2)*win_aspect)
{
if(y_pos <= y_brick[b][a] && y_pos >= y_brick[b][a] - 0.1)
{
if(show[b][a] == 1)
{
show[b][a] = 0;
flag = 0;
hit = true;
break;
}
}
}
}
if(flag == 0)
break;
}
phit_corner = false;
phit_center = false;
if(x_pos <= (P_XPOS + P_LENGTH - 0.05)&& x_pos >= (P_XPOS - P_LENGTH - 0.05))
{
if(y_pos <= P_YPOS)
{
phit_center = true;
}
}
else if((x_pos >=(P_XPOS + P_LENGTH - 0.05) && x_pos <= (P_XPOS + P_LENGTH)) || (x_pos <= (P_XPOS - P_LENGTH + 0.05) && x_pos >= P_XPOS - P_LENGTH))
{
if(y_pos <= P_YPOS)
{
phit_corner = true;
}
}
if(phit_center)
{
DOWN = false;
UP = true;
}
if(phit_corner)
{
if(LEFT)
{
LEFT = false;
RIGHT = true;
}
else
{
RIGHT = false;
LEFT = true;
}
UP = false;
DOWN = true;
}
if(crashed())
{
x_pos = 0;
y_pos = -0.7;
started = false;
UP = true;
RIGHT = true;
DOWN = false;
LEFT = false;
}
BallLoop();
}
void ArrowKeys(int key, int x, int y)
{
if(key==GLUT_KEY_LEFT && P_XPOS >= -0.9*win_aspect)
{
for(float a = 0; a < 0.05; a+= 0.001)
{
P_XPOS -=0.002;
GameLogic();
}
if(!started)
started = true;
}
if(key==GLUT_KEY_RIGHT && P_XPOS <= 0.9*win_aspect)
{
for(float a = 0; a < 0.05; a+= 0.001)
{
P_XPOS +=0.002;
GameLogic();
}
if(!started)
started = true;
}
}
void Init_Game()
{
int c = 0;
for(float a = -0.94; c < BRICK_COL; a+=0.21)
{
for(int b = 0; b <= BRICK_ROW; b++)
{
x_brick[b][c] = a;
}
c++;
}
c = 0;
for(float a = 0.99; c < BRICK_ROW; a-=0.11)
{
for(int b = 0; b < BRICK_COL; b++)
{
y_brick[c][b] = a;
}
c++;
}
}
void set_speed()
{
clock_t start = clock();
for(int a = 1; a < 99999999LLU; a+= 1)
{
;
}
clock_t end = clock();
SPEED = (double)(end - start)/CLOCKS_PER_SEC;
SPEED /= 800;
}
int main(int argc, char **argv)
{
set_speed();
Init_Game();
SET_BRICKS(LEVEL);
Set_Level(LEVEL);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(0,0);
glutInitWindowSize(WIDTH,HEIGHT);
glutCreateWindow("Brick Breaker - By Viraj");
glutKeyboardFunc(user_input);
glutSpecialFunc(ArrowKeys);
glutIdleFunc(GameLogic);
glutDisplayFunc(BallLoop);
glutMainLoop();
return 0;
}
Please take a look at the corrected version of your code I posted as answer to your original question. Brick Breaker help. circles, paddles, and awkward bouncing
Reposting the GLFW version here again, for simplicity:
#include <GL/glfw.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
using namespace std;
#define RADIUS 0.025
#define RATIO (4./3.)
bool show[5][10];
float x_brick[4][9];
float y_brick[4][9];
const float SpeedFactor = 1.;
float paddle_x = 0;
float paddle_y = -0.8;
float paddle_speed = 0;
const float PaddleSpeedFactor = 3.;
bool phit_center = false, phit_corner = false;
bool game_over = false;
float speed_x = 0.;
float speed_y = 0.;
float x_pos;
float y_pos;
int lifes = 0;
void draw_bricks()
{
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_QUADS);
for (int a = 0; a < 9; a++) {
for (int b = 0; b < 4; b++) {
if (show[b][a] == 1) {
glVertex2f(x_brick[b][a], y_brick[b][a]);
glVertex2f(x_brick[b][a], y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a] + 0.2,
y_brick[b][a] - 0.10);
glVertex2f(x_brick[b][a] + 0.2, y_brick[b][a]);
}
}
}
glEnd();
}
void ball_draw()
{
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x_pos, y_pos);
for (float angle = 0; angle < (10); angle += 0.01) {
glVertex2f((x_pos + sin(angle) * RADIUS),
(y_pos + (cos(angle)) * RADIUS));
}
glEnd();
}
bool brick_hit()
{
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 4; b++) {
if (x_pos >= x_brick[b][a]
&& x_pos <= x_brick[b][a] + 0.2) {
if (y_pos <= y_brick[b][a]
&& y_pos >= y_brick[b][a] - 0.1) {
if (show[b][a] == 1) {
show[b][a] = 0;
return true;
}
}
}
}
}
return false;
}
bool crashed()
{
if (y_pos < paddle_y - 0.05)
return true;
return false;
}
void paddle_hit()
{
phit_corner = false;
phit_center = false;
if (x_pos <= paddle_x + 0.13 && x_pos >= paddle_x - 0.13) {
if (y_pos <= paddle_y) {
phit_center = true;
}
} else if ((x_pos >= paddle_x + 0.13 && x_pos <= paddle_x + 0.2) ||
(x_pos <= paddle_x - 0.13 && x_pos >= paddle_x - 0.2)) {
if (y_pos <= paddle_y) {
phit_corner = true;
}
}
}
void paddle_move(float dT)
{
if (paddle_x < RATIO && paddle_x > -RATIO)
paddle_x += paddle_speed * PaddleSpeedFactor * dT;
if (paddle_x > 1.) {
paddle_x = 1.;
paddle_speed = 0.;
}
if (paddle_x < -1.) {
paddle_x = -1.;
paddle_speed = 0.;
}
}
void ball_move(float dT)
{
x_pos += speed_x * dT;
y_pos += speed_y * dT;
if (brick_hit()) {
speed_y *= -1;
}
if (x_pos >= (RATIO - RADIUS) || x_pos <= (-RATIO + RADIUS)) {
speed_x *= -1;
}
if (y_pos >= (1. - RADIUS)) {
speed_y *= -1;
}
paddle_hit();
if (phit_center) {
speed_y *= -1;
speed_x += 0.5 * paddle_speed;
}
if (phit_corner) {
speed_x = -speed_x + 0.2 * paddle_speed;
speed_y *= -1;
}
if( (speed_x * speed_x + speed_y * speed_y) > 0.001 ) {
float k = 1./sqrt(speed_x * speed_x + speed_y * speed_y);
speed_x *= k;
speed_y *= k;
}
}
void paddle_draw()
{
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_QUADS);
glVertex2f(paddle_x - 0.2, paddle_y);
glVertex2f(paddle_x + 0.2, paddle_y);
glVertex2f(paddle_x + 0.2, paddle_y - 0.05);
glVertex2f(paddle_x - 0.2, paddle_y - 0.05);
glEnd();
}
void set_xy();
void reset_game()
{
set_xy();
lifes = 3;
speed_x = 0;
speed_y = 0;
x_pos = 0;
y_pos = -0.7;
paddle_speed = 0;
paddle_x = 0;
}
void step_game(float dT)
{
if(!lifes)
return;
paddle_move(dT * SpeedFactor);
ball_move(dT * SpeedFactor);
if (crashed()) {
lifes--;
speed_x = 0;
speed_y = 0;
x_pos = 0;
y_pos = -0.7;
}
}
static float frandom(float a, float b)
{
return a + (b - a) * (float)random() / (float)RAND_MAX;
}
void launch_ball()
{
if(!lifes)
return;
speed_y = 1.;
speed_x = frandom(-1., 1.);
float k = 1./sqrt(speed_x * speed_x + speed_y + speed_y);
speed_x *= k;
speed_y *= k;
}
void keyboard(int key, int action)
{
switch(key)
{
case GLFW_KEY_ENTER:
launch_ball();
break;
case GLFW_KEY_ESC:
reset_game();
break;
case GLFW_KEY_LEFT:
switch(action) {
case GLFW_PRESS:
paddle_speed = -1.;
break;
case GLFW_RELEASE:
paddle_speed = 0;
break;
} break;
case GLFW_KEY_RIGHT:
switch(action) {
case GLFW_PRESS:
paddle_speed = 1.;
break;
case GLFW_RELEASE:
paddle_speed = 0;
break;
} break;
}
}
void set_xy()
{
for (int a = 0; a < 5; a++) {
for (int b = 0; b < 10; b++) {
show[a][b] = 1;
}
}
int c = 0;
for (float a = -0.94; c <= 8; a += 0.21, c++) {
for (int b = 0; b <= 5; b++) {
x_brick[b][c] = a;
}
}
int d = 0;
for (float s = 0.99; d <= 3; s -= 0.11, d++) {
for (int r = 0; r < 9; r++) {
y_brick[d][r] = s;
}
}
}
float display()
{
int win_width;
int win_height;
glfwGetWindowSize(&win_width, &win_height);
const float win_aspect = (float)win_width / (float)win_height;
glfwSetTime(0.);
glViewport(0, 0, win_width, win_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (win_aspect > RATIO) {
glOrtho(-win_aspect, win_aspect, -1., 1., -1., 1.);
} else {
glOrtho(-RATIO, RATIO, -RATIO / win_aspect, RATIO / win_aspect,
-1., 1.);
}
glMatrixMode(GL_MODELVIEW);
glClearColor(0., 0., 1., 1.);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
glVertex2f(-RATIO, -1);
glVertex2f(RATIO, -1);
glVertex2f(RATIO, 1);
glVertex2f(-RATIO, 1);
glEnd();
draw_bricks();
paddle_draw();
ball_draw();
glfwSwapBuffers();
return glfwGetTime();
}
int main(int argc, char **argv)
{
srandom(time(0));
set_xy();
if( GL_FALSE == glfwInit() )
return -1;
if( GL_FALSE == glfwOpenWindow(800, 600, 8, 8, 8, 8, 0, 0, GLFW_WINDOW) )
return -2;
glfwSetWindowTitle("Viraj's Brick Breaker - GLFW version by datenwolf");
glfwSetKeyCallback(keyboard);
reset_game();
while( glfwGetWindowParam(GLFW_OPENED) ) {
glfwPollEvents();
float const dT = display();
step_game(dT);
}
glfwTerminate();
return 0;
}
I'm just telling this, because the code you posted above is (again) an utter mess. Also notice how I count down the lifes, and introduced a function reset_game that will put things back to starting conditions.
BTW: Your coding style is a mess. It looks like you've done a lot of BASIC (GW-BASIC or QBASIC programming) and are still mentally stuck in that world.
For example you should reset the game field through a single entry function, that then calls specialized functions for each reset step. Then you just call that reset function, instead of trying to keep track of all variables.
I understand that the new code in your question has new features, but you still need to restructure a few things.
One of the biggest mistakes of yours is, that you still mix input with animation:
void ArrowKeys(int key, int x, int y)
{
if(key==GLUT_KEY_LEFT && P_XPOS >= -0.9*win_aspect)
{
for(float a = 0; a < 0.05; a+= 0.001)
{
P_XPOS -=0.002;
GameLogic();
}
That inner for loop will animate the paddle in reaction to the key, and while this animation happens all further user input will pile up, leading to strange movements. Never do this. In a input handler set some state variable, that influences the GameLogic in the idle loop. But never directly animate from the input handler!
Please take a look at my code, compile it, execute it. And try to understand the separation between game logic, rendering and input processing.