-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameRunner.java
More file actions
82 lines (69 loc) · 2.45 KB
/
Copy pathGameRunner.java
File metadata and controls
82 lines (69 loc) · 2.45 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
import java.lang.Thread;
import java.util.concurrent.Semaphore;
import java.awt.Point;
import java.awt.Polygon;
public class GameRunner extends Thread {
Camera camera;
Controls controls;
Semaphore lock = new Semaphore(1, true);
public GameRunner(Camera cam, Controls controller) {
camera = cam;
controls = controller;
}
public void run() {
System.out.println("let's go");
while (true) {
int sleepTime = 1000 / 60;
try {
Thread.sleep(sleepTime);
lock.acquire();
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
updateScene(sleepTime * 1.0 / 1000);
camera.repaint();
lock.release();
}
}
public void loadScene(Scene scene) {
try { lock.acquire(); } catch (Exception e) {}
camera.scene = scene;
lock.release();
System.out.println("reset");
}
public void updateScene(double timeEllapsed) {
if (controls.r) {
camera.scene.reset();
return;
}
Sprite spaceShip = camera.scene.spaceShip;
for (Planet planet : camera.scene.planets) {
double dx = planet.xPosition - spaceShip.xPosition;
double dy = planet.yPosition - spaceShip.yPosition;
double distanceSquared = Math.pow(dx, 2) + Math.pow(dy, 2);
double force = Planet.gravityStrength * planet.mass / distanceSquared;
double theta = Math.atan2(dy, dx);
double forceX = Math.cos(theta) * force;
double forceY = Math.sin(theta) * force;
spaceShip.xVelocity += forceX * timeEllapsed;
spaceShip.yVelocity += forceY * timeEllapsed;
if (Math.sqrt(distanceSquared) < planet.radius) {
spaceShip.yVelocity = 0;
spaceShip.xVelocity = 0;
return;
}
}
if (controls.w) {
spaceShip.yVelocity += Math.cos(spaceShip.rotation) * -10;
spaceShip.xVelocity += Math.sin(spaceShip.rotation) * 10;
}
if (controls.a) {
spaceShip.rotation -= Math.PI / 32;
}
if (controls.d) {
spaceShip.rotation += Math.PI / 32;
}
spaceShip.xPosition += spaceShip.xVelocity * timeEllapsed;
spaceShip.yPosition += spaceShip.yVelocity * timeEllapsed;
}
}