-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBall.cpp
More file actions
58 lines (46 loc) · 1.05 KB
/
Ball.cpp
File metadata and controls
58 lines (46 loc) · 1.05 KB
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
#include "Ball.h"
#include "Constants.h"
const float Ball::SPEED = 445.f;
Ball::Ball(sf::Vector2f position, float size_set)
{
direction = sf::Vector2f(randomDirection(), 0.f);
size = size_set;
setPosition(position);
}
void Ball::update(const float DT)
{
// Horizontal Collision
if (getPosition().y <= 0.f)
direction.y = -direction.y;
if (getPosition().y >= WINDOW_HEIGHT - size)
direction.y = -direction.y;
move(direction * SPEED * DT);
}
void Ball::hit(const Paddle &paddle)
{
direction.x = -direction.x;
if (paddle.getVelocity() > 0)
direction.y = 1.f;
if (paddle.getVelocity() < 0)
direction.y = -1.f;
}
void Ball::reset()
{
setPosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2);
direction = sf::Vector2f(randomDirection(), 0.f);
}
void Ball::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
sf::RectangleShape ball(sf::Vector2f(size, size));
ball.setPosition(getPosition());
target.draw(ball);
}
float Ball::randomDirection() const
{
int choices = rand() % 2;
// Left
if (choices == 0)
return -1.f;
// Right
return 1.f;
}