Repository navigation
Expand file tree
/
Copy pathEnemyBullet.java
More file actions
101 lines (88 loc) · 3.54 KB
/
Copy pathEnemyBullet.java
File metadata and controls
101 lines (88 loc) · 3.54 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
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.animation.AnimationTimer;
import javafx.scene.Node;
// The EnemyBullet class represents a projectile fired by an enemy tank.
public class EnemyBullet extends ImageView {
// Fields
private static final int SPEED = 5;
private AnimationTimer timer;
private boolean paused = false;
// Constructs an EnemyBullet at the specified location and direction.
public EnemyBullet(double x, double y, String direction, GameManager gameManager) {
Image bulletImage = new Image("file:assets/bullet.png");
setImage(bulletImage);
setFitWidth(10);
setFitHeight(13);
setTranslateX(x);
setTranslateY(y);
int xVelocity = 0;
int yVelocity = 0;
int rotationAngle = 0;
// Determine movement vector and rotation angle based on direction
switch (direction) {
case "UP":
yVelocity = -1;
rotationAngle = 270;
break;
case "DOWN":
yVelocity = 1;
rotationAngle = 90;
break;
case "LEFT":
xVelocity = -1;
rotationAngle = 180;
break;
case "RIGHT":
xVelocity = 1;
rotationAngle = 0;
break;
}
final int finalXVelocity = xVelocity;
final int finalYVelocity = yVelocity;
setRotate(rotationAngle);
// Add bullet to game scene
gameManager.getChildren().add(this);
// AnimationTimer to move the bullet each frame
timer = new AnimationTimer() {
@Override
public void handle(long now) {
if (paused) return;
// Move bullet in the specified direction
setTranslateX(getTranslateX() + finalXVelocity * SPEED);
setTranslateY(getTranslateY() + finalYVelocity * SPEED);
// Remove bullet if it leaves screen boundaries
if (getTranslateX() < 0 || getTranslateX() > 800 ||
getTranslateY() < 0 || getTranslateY() > 700) {
stop();
gameManager.getChildren().remove(EnemyBullet.this);
return;
}
// Collision detection with player and walls
for (Node node : gameManager.getChildren()) {
// Hit the player
if (node instanceof Player &&
getBoundsInParent().intersects(node.getBoundsInParent())) {
stop();
gameManager.getChildren().remove(EnemyBullet.this);
gameManager.hitPlayer();
break;
}
// Hit a wall
if (node instanceof Wall &&
getBoundsInParent().intersects(node.getBoundsInParent())) {
stop();
new SmallExplosion(getTranslateX(), getTranslateY(), gameManager);
gameManager.getChildren().remove(EnemyBullet.this);
break;
}
}
}
};
timer.start(); // Start bullet movement
}
// Pauses or resumes bullet movement.
public void setPaused(boolean value) {
this.paused = value;
}
}