/
ball.cpp
99 lines (77 loc) · 1.42 KB
/
ball.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
#include <GL/gl.h>
#include <cstdlib>
#include "ball.h"
Ball::Ball()
{
moveToCenter();
}
const float Ball::SPEED;
float Ball::top()
{
return y;
}
float Ball::bottom()
{
return y - WIDTH;
}
float Ball::left()
{
return x;
}
float Ball::right()
{
return x + WIDTH;
}
bool Ball::isLeftBound()
{
return xVelocity < 0;
}
bool Ball::isRightBound()
{
return xVelocity > 0;
}
float Ball::speed()
{
return Ball::SPEED;
}
void Ball::moveToCenter()
{
x = MIDDLE_X;
y = 0;
xVelocity = rand() % 2 == 0 ? SPEED : -SPEED;
yVelocity = rand() % 2 == 0 ? Ball::SPEED : -Ball::SPEED;
}
void Ball::draw()
{
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
//top right
glTexCoord2f(1.0, 1.0);
glVertex3f(right(), top(), ARENA_LEVEL);
//top left
glTexCoord2f(0.0, 1.0);
glVertex3f(left(), top(), ARENA_LEVEL);
//bottom left
glTexCoord2f(0.0, 0.0);
glVertex3f(left(), bottom(), 3);
//bottom right
glTexCoord2f(1.0, 0.0);
glVertex3f(right(), bottom(), ARENA_LEVEL);
glEnd();
glDisable(GL_TEXTURE_2D);
}
void Ball::updateFrame(float elapsed)
{
x += xVelocity * elapsed;
y += yVelocity * elapsed;
}
void Ball::bounceHorizontally()
{
x = xVelocity < 0 ? ARENA_LEFT : ARENA_RIGHT - WIDTH;
xVelocity = -xVelocity;
}
void Ball::bounceVertically()
{
y = yVelocity < 0 ? ARENA_BOTTOM + WIDTH : ARENA_TOP;
yVelocity = -yVelocity;
}