-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBall.cpp
More file actions
89 lines (77 loc) · 1.89 KB
/
Ball.cpp
File metadata and controls
89 lines (77 loc) · 1.89 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
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
#include "Ball.h"
Ball::Ball()
{
radius = RADIUS;
pos = Vector2D();
speed = Vector2D();
}
Ball::Ball(float x, float y) {
radius = RADIUS;
pos = Vector2D(x, y);
speed = Vector2D();
}
Ball::Ball(float x, float y, float vx, float vy) {
radius = RADIUS;
pos = Vector2D(x, y);
speed = Vector2D(vx, vy);
}
void Ball::update(float w, float h) {
// Update speed based on TIME_STEP.
pos = pos + (speed * TIME_STEP);
// Check for collisions with walls and reflect speed accordingly.
if (pos.getX() + RADIUS > w || pos.getX() - RADIUS < 0) {
speed.setX(-speed.getX());
// Remember to "push" ball out of the wall as well.
if (pos.getX() - RADIUS < 0) {
pos.setX(RADIUS);
}
if (pos.getX() + RADIUS > w) {
pos.setX(w - RADIUS);
}
}
if (pos.getY() + RADIUS > h || pos.getY() - RADIUS < 0) {
speed.setY((-speed.getY()));
// Remember to "push" ball out of the wall as well.
if (pos.getY() - RADIUS < 0) {
pos.setY(RADIUS);
}
if (pos.getY() + RADIUS < w) {
pos.setY(w - RADIUS);
}
}
}
void Ball::decelerate() {
// Decrease speed based on DRAG factor and TIME_STEP.
float change = DRAG * TIME_STEP;
// If speed is low enough, then set to 0. Else decrease speed.
if (speed.getMagnitude() < 0.05) {
speed.setX(0);
speed.setY(0);
}
else {
speed = speed * (1 - (change / speed.getMagnitude()));
}
}
float Ball::distance(Ball b2) {
float result = pos.getDist(b2.getPos());
return result;
}
float Ball::getRadius() {
return radius;
}
Vector2D Ball::getPos() {
return pos;
}
Vector2D Ball::getSpeed() {
return speed;
}
void Ball::setPos(Vector2D newPos) {
pos = newPos;
}
void Ball::setSpeed(Vector2D newSpeed) {
speed = newSpeed;
}
Ball::~Ball()
{
//dtor
}