-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStar.java
More file actions
69 lines (60 loc) · 2.29 KB
/
Star.java
File metadata and controls
69 lines (60 loc) · 2.29 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
import java.awt.*;
public class Star {
private float x;
private float y;
private float xSpeed;
private float ySpeed;
private float prevX;
private float prevY;
public Star() {
x = (float) StarfieldSimulation.WIDTH/2;
y = (float) StarfieldSimulation.HEIGHT/2;
while (x == StarfieldSimulation.WIDTH/2 && y == StarfieldSimulation.HEIGHT/2) {
x = (float) (Math.random() * StarfieldSimulation.WIDTH/4 + StarfieldSimulation.WIDTH*3/8);
y = (float) (Math.random() * StarfieldSimulation.HEIGHT/4 + StarfieldSimulation.HEIGHT*3/8);
}
setSpeed();
}
public void setSpeed() {
// the speed direction is colinear to the vector from the center of the screen to the star
float xCenter = StarfieldSimulation.WIDTH/2;
float yCenter = StarfieldSimulation.HEIGHT/2;
float dx = x - xCenter;
float dy = y - yCenter;
float norm = (float) Math.sqrt(dx*dx + dy*dy);
xSpeed = dx/50 * StarfieldSimulation.SPEED;
ySpeed = dy/50 * StarfieldSimulation.SPEED;
}
public void update() {
setSpeed();
prevX = x;
prevY = y;
x += xSpeed;
y += ySpeed;
//if the star is out of the screen
if (x > StarfieldSimulation.WIDTH || x < 0 || y > StarfieldSimulation.HEIGHT || y < 0) {
x = (float) (Math.random() * StarfieldSimulation.WIDTH/2 + StarfieldSimulation.WIDTH/4);
y = (float) (Math.random() * StarfieldSimulation.HEIGHT/2 + StarfieldSimulation.HEIGHT/4);
prevX = x;
prevY = y;
setSpeed();
}
}
public void render(Graphics g) {
float xCenter = StarfieldSimulation.WIDTH/2;
float yCenter = StarfieldSimulation.HEIGHT/2;
float norm = (float) Math.sqrt((x - xCenter)*(x - xCenter) + (y - yCenter)*(y - yCenter));
float maxnorm = (float) Math.sqrt((xCenter)*(xCenter) + (yCenter)*(yCenter));
Graphics2D g2d = (Graphics2D) g;
float thickness = 1 + (norm/maxnorm);
g2d.setStroke(new BasicStroke(thickness));
g.setColor(Color.WHITE);
g.drawLine((int) prevX, (int) prevY, (int) x, (int) y);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}