Repository navigation
Expand file tree
/
Copy pathBall.java
More file actions
116 lines (94 loc) · 2.69 KB
/
Copy pathBall.java
File metadata and controls
116 lines (94 loc) · 2.69 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.javarush.task.task24.task2413;
/**
* Класс для шарика в игре
*/
public class Ball extends BaseObject {
// скорость
private double speed;
// направление (в градусах от 0 до 360)
private double direction;
// текущее значение вектора движения (dx,dy)
private double dx;
private double dy;
// заморожен ли объект или может двигаться
private boolean isFrozen;
public Ball(double x, double y, double speed, double direction) {
super(x, y, 1);
this.direction = direction;
this.speed = speed;
this.isFrozen = true;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getDirection() {
return direction;
}
public double getDx() {
return dx;
}
public double getDy() {
return dy;
}
/**
* Устанавливаем новое направление движения.
* Тут же вычисляем и новый вектор.
* Такой подход удобно использовать при отскоках от стен.
*/
void setDirection(double direction) {
this.direction = direction;
double angle = Math.toRadians(direction);
dx = Math.cos(angle) * speed;
dy = -Math.sin(angle) * speed;
}
/**
* Рисуем себя на "канвасе".
*/
@Override
void draw(Canvas canvas) {
canvas.setPoint(x, y, 'O');
}
/**
* Двигаем себя на один шаг.
*/
public void move() {
if (isFrozen) return;
x += dx;
y += dy;
checkRebound(1, Arkanoid.game.getWidth(), 1, Arkanoid.game.getHeight() + 5);
}
/**
* Проверяем не улетел ли шарик за стенку.
* Если да - отражаем его.
*/
void checkRebound(int minx, int maxx, int miny, int maxy) {
if (x < minx) {
x = minx + (minx - x);
dx = -dx;
}
if (x > maxx) {
x = maxx - (x - maxx);
dx = -dx;
}
if (y < miny) {
y = miny + (miny - y);
dy = -dy;
}
if (y > maxy) {
y = maxy - (y - maxy);
dy = -dy;
}
}
/**
* Запускам шарик.
* isFrozen = false.
* Пересчитываем вектор движения (dx,dy).
*/
void start() {
this.setDirection(direction);
this.isFrozen = false;
}
}