-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ball.cpp
92 lines (65 loc) · 1.79 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
#include "Ball.h"
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
Ball::Ball(float startX, float startY, sf::Texture &texture)
{
texture.setSmooth(true);
shape.setRadius(10.f);
shape.setOrigin(shape.getRadius(), shape.getRadius());
shape.setPosition(startX, startY);
shape.setTexture(&texture);
if (!wallHitBuffer.loadFromFile("./sounds/wallHit.wav"))
{
// error...
}
wallHit.setBuffer(wallHitBuffer);
wallHit.setVolume(50);
if (!brickHitBuffer.loadFromFile("./sounds/brickHit.ogg"))
{
// error...
}
brickHit.setBuffer(brickHitBuffer);
this->shape = shape;
}
Ball::~Ball()
{
}
void Ball::update()
{
if (gameStopped) {
velocity.x = 0;
velocity.y = 0;
Ball::shape.setPosition(windowWidth / 2, windowHeight - 75);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
gameStopped = false;
velocity.x = -ballVelocity;
velocity.y = -ballVelocity;
}
return;
}
shape.move(velocity);
shape.rotate(5.f);
// We need to keep the ball "inside the screen".
// If it's leaving toward the left, we need to set
// horizontal velocity to a positive value (towards the right).
if (left() < 0) {
velocity.x = ballVelocity;
wallHit.play();
}
// Otherwise, if it's leaving towards the right, we need to
// set horizontal velocity to a negative value (towards the left).
else if (right() > windowWidth)
{
velocity.x = -ballVelocity;
wallHit.play();
}
// The same idea can be applied for top/bottom collisions.
if (top() < 0)
velocity.y = ballVelocity;
}
void Ball::reset()
{
shape.setPosition(windowWidth / 2, windowHeight - 75);
velocity.x = -ballVelocity;
velocity.y = -ballVelocity;
}