-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPhysics.java
More file actions
522 lines (448 loc) · 21.8 KB
/
Copy pathPhysics.java
File metadata and controls
522 lines (448 loc) · 21.8 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*
* Authors: Jerry Li & Victor Jiang
* Date: June 13, 2025
* Description: This class handles physics related calculations in the game
*/
import java.awt.Rectangle;
import java.util.List;
public class Physics {
// Reusable vectors to avoid per-frame allocations
private static final Vector TMP_NORMAL = new Vector();
private static final Vector TMP_REL = new Vector();
private static final Vector TMP_TANGENT = new Vector();
private static final Vector TMP_IMPULSE = new Vector();
private static final Vector TMP_FRICTION = new Vector();
// Constants for various physics parameters
public static final float PUSH_FORCE = 14f;
public static final float ENEMY_SEPARATION_GAP = 2.5f;
public static final float COLLISION_RESTITUTION = 0.65f;
public static final float COLLISION_FRICTION = 0.2f;
public static final float FLOATING_POINT_EPSILON = 1e-4f;
public static final float COLLISION_SLOP = 0.01f;
public static final float POSITION_BIAS_FACTOR = 0.2f;
public static final float CONTINUOUS_COLLISION_THRESHOLD = 8f;
private static final float CONTINUOUS_COLLISION_THRESHOLD_SQ =
CONTINUOUS_COLLISION_THRESHOLD * CONTINUOUS_COLLISION_THRESHOLD;
public static final float PLAYER_ENTITY_MASS = 2.0f;
public static final float ANGEL_ENTITY_MASS = 1.5f;
public static final float ENEMY_ENTITY_MASS = 1.0f;
// public constructor to prevent instantiation of this utility class
public Physics() {
}
// Resolves collisions between the player, enemies, and other entities in the
// game
public static void resolveCollisions(GameState state, Player player, List<Enemy> enemies, List<Angel> angels, float dt, SpatialHashGrid<Entity> grid) {
float dt_scale;
// Only resolve collisions if the game state is "PLAYING"
if (state != GameState.PLAYING)
return;
// Scale the delta time to ensure consistent behavior
dt_scale = Math.min(dt * 60f, 2.0f);
// Resolve collisions between the player and enemies
resolvePlayerEnemyCollisions(player, enemies, dt_scale, grid);
// Resolve collisions between enemies
resolveEnemyEnemyCollisions(enemies, dt_scale, grid);
// Resolve collisions between angels and enemies
resolveAngelEnemyCollisions(angels, enemies, dt_scale, grid);
// Resolve collisions between angels
resolveAngelAngelCollisions(angels, dt_scale, grid);
}
// Resolves collisions between the player and enemies
public static void resolvePlayerEnemyCollisions(Player player, List<Enemy> enemies, float dt_scale, SpatialHashGrid<Entity> grid) {
Rectangle player_broadphase;
float searchRad;
java.util.Iterator<Entity> qIt;
Entity ent = null;
Enemy enemy = null;
Rectangle enemy_broadphase;
Vector normal;
float distance;
float penetration;
float total_mass;
float enemy_ratio;
float push_factor;
Vector relative_vel;
float base_push;
float angle_bonus;
float final_force;
// Get the player's bounding box and expand it based on velocity
player_broadphase = player.getBounds();
expandRectByVelocity(player_broadphase, player.getXVelocity(), player.getYVelocity());
// Query nearby enemies using the spatial grid
searchRad = player.getRadius() + player.MAX_SPEED * 2f;
qIt = grid.queryNearby((float) player.getCenterX(), (float) player.getCenterY(), searchRad).iterator();
while (qIt.hasNext()) {
ent = qIt.next();
if (!(ent instanceof Enemy))
continue;
enemy = (Enemy) ent;
if (enemy.isIntangible())
continue;
// Get the enemy's bounding box and expand it based on velocity
enemy_broadphase = enemy.getBounds();
expandRectByVelocity(enemy_broadphase, enemy.getXVelocity(), enemy.getYVelocity());
// Skip if the player's and enemy's bounding boxes do not intersect
if (!player_broadphase.intersects(enemy_broadphase))
continue; // Check if the player and enemy circles intersect
if (circleIntersection(player, enemy)) {
// Apply damage to the player only if not invulnerable
if (!player.isInvulnerable()) {
player.takeDamage(enemy.getDamage());
}
enemy.takeDamage(player.parent.getCurrentWave());
// Calculate the collision normal vector
normal = TMP_NORMAL;
normal.set(
(float) (player.getCenterX() - enemy.getCenterX()),
(float) (player.getCenterY() - enemy.getCenterY()));
distance = normal.length();
// Handle cases where the distance is too small to avoid division by zero
if (distance < FLOATING_POINT_EPSILON) {
normal.set((float) Math.random() * 2 - 1, (float) Math.random() * 2 - 1).normalize();
} else {
normal.scale(1f / distance);
}
// Calculate the penetration depth
penetration = enemy.getRadius() + player.getRadius() - distance;
// Resolve penetration by adjusting the enemy's position
if (penetration > 0f) {
total_mass = PLAYER_ENTITY_MASS + ENEMY_ENTITY_MASS;
enemy_ratio = PLAYER_ENTITY_MASS / total_mass;
push_factor = PUSH_FORCE * dt_scale;
penetration += push_factor * enemy_ratio;
enemy.setPos(
enemy.getCenterX() - normal.x * penetration * enemy_ratio,
enemy.getCenterY() - normal.y * penetration * enemy_ratio);
}
// Calculate the relative velocity between the player and enemy
relative_vel = TMP_REL;
relative_vel.set(
enemy.getXVelocity() - player.getXVelocity(),
enemy.getYVelocity() - player.getYVelocity());
// Apply knockback to the enemy based on the collision
base_push = 10.0f * dt_scale;
angle_bonus = 1.0f + Math.max(0, -relative_vel.dot(normal) / 10.0f);
final_force = base_push * angle_bonus;
enemy.applyKnockback(
-normal.x * final_force,
-normal.y * final_force);
}
}
}
public static void resolveAngelEnemyCollisions(List<Angel> angels, List<Enemy> enemies, float dt_scale, SpatialHashGrid<Entity> grid) {
Angel angel = null;
Rectangle angel_broadphase = null;
float searchRad = 0f;
int i = 0;
Entity ent = null;
Enemy enemy = null;
java.util.Iterator<Entity> qIt;
Rectangle enemy_broadphase;
int dmg;
Archangel arch;
Vector normal;
float distance;
float penetration;
float total_mass;
float enemy_ratio;
float push_factor;
Vector relative_vel;
float base_push;
float angle_bonus;
float final_force;
for (i = 0; i < angels.size(); i++) {
angel = angels.get(i);
// Get the angel's bounding box and expand it based on velocity
angel_broadphase = angel.getBounds();
expandRectByVelocity(angel_broadphase, angel.getXVelocity(), angel.getYVelocity());
searchRad = angel.getRadius() * 2f + ENEMY_SEPARATION_GAP;
qIt = grid.queryNearby((float) angel.getCenterX(), (float) angel.getCenterY(), searchRad).iterator();
while (qIt.hasNext()) {
ent = qIt.next();
if (!(ent instanceof Enemy))
continue;
enemy = (Enemy) ent;
// Get the enemy's bounding box and expand it based on velocity
enemy_broadphase = enemy.getBounds();
expandRectByVelocity(enemy_broadphase, enemy.getXVelocity(), enemy.getYVelocity());
if (!angel_broadphase.intersects(enemy_broadphase))
continue;
if (enemy.isBoss())
continue; // Skip boss enemies for angel collisions
// Check if the player and enemy circles intersect
if (circleIntersection(angel, enemy)) {
// Apply damage to the player
angel.takeDamage(1);
dmg = angel.damage;
if (angel instanceof Archangel) {
arch = (Archangel) angel;
dmg += arch.getBonusDamage();
}
enemy.takeDamage(dmg);
// Calculate the collision normal vector
normal = TMP_NORMAL;
normal.set(
(float) (angel.getCenterX() - enemy.getCenterX()),
(float) (angel.getCenterY() - enemy.getCenterY()));
distance = normal.length();
// Handle cases where the distance is too small to avoid division by zero
if (distance < FLOATING_POINT_EPSILON) {
normal.set((float) Math.random() * 2 - 1, (float) Math.random() * 2 - 1).normalize();
} else {
normal.scale(1f / distance);
}
// Calculate the penetration depth
penetration = enemy.getRadius() + angel.getRadius() - distance;
// Resolve penetration by adjusting the enemy's position
if (penetration > 0f) {
total_mass = ANGEL_ENTITY_MASS + ENEMY_ENTITY_MASS;
enemy_ratio = ANGEL_ENTITY_MASS / total_mass;
push_factor = PUSH_FORCE * dt_scale;
penetration += push_factor * enemy_ratio;
enemy.setPos(
enemy.getCenterX() - normal.x * penetration * enemy_ratio,
enemy.getCenterY() - normal.y * penetration * enemy_ratio);
}
// Calculate the relative velocity between the player and enemy
relative_vel = TMP_REL;
relative_vel.set(
enemy.getXVelocity() - angel.getXVelocity(),
enemy.getYVelocity() - angel.getYVelocity());
// Apply knockback to the enemy based on the collision
base_push = 10.0f * dt_scale;
angle_bonus = 1.0f + Math.max(0, -relative_vel.dot(normal) / 10.0f);
final_force = base_push * angle_bonus;
enemy.applyKnockback(
-normal.x * final_force,
-normal.y * final_force);
}
}
}
}
// Resolves collisions between enemies
public static void resolveEnemyEnemyCollisions(List<Enemy> enemies, float dt_scale, SpatialHashGrid<Entity> grid) {
Enemy a = null;
float searchRad = 0f;
Entity ent = null;
Enemy b = null;
int i = 0;
java.util.Iterator<Entity> qIt;
Vector normal;
float distance;
float target_distance;
float penetration;
float correction;
Vector rel_vel;
float vel_along_normal;
float restitution;
float impulse_scalar;
Vector impulse;
Vector tangent;
float vel_along_tangent;
float friction_impulse;
Vector friction_vec;
float a_speed_sq = 0f;
float b_speed_sq = 0f;
boolean a_moving_fast = false;
for (i = 0; i < enemies.size(); i++) {
a = enemies.get(i);
searchRad = a.getRadius() * 2f + ENEMY_SEPARATION_GAP;
qIt = grid.queryNearby((float) a.getCenterX(), (float) a.getCenterY(), searchRad).iterator();
while (qIt.hasNext()) {
ent = qIt.next();
if (!(ent instanceof Enemy))
continue;
b = (Enemy) ent;
if (a == b)
continue;
a_speed_sq = a.getXVelocity() * a.getXVelocity() + a.getYVelocity() * a.getYVelocity();
b_speed_sq = b.getXVelocity() * b.getXVelocity() + b.getYVelocity() * b.getYVelocity();
a_moving_fast = a_speed_sq > 0.25f;
if (!a_moving_fast && !(b_speed_sq > 0.25f))
continue;
// Skip if the enemies' circles do not intersect
if (!circleIntersection(a, b))
continue;
// Calculate the collision normal vector
normal = TMP_NORMAL;
normal.set(
(float) (a.getCenterX() - b.getCenterX()),
(float) (a.getCenterY() - b.getCenterY()));
distance = normal.length();
// Handle cases where the distance is too small to avoid division by zero
if (distance < FLOATING_POINT_EPSILON) {
normal.set((float) Math.random() * 2 - 1, (float) Math.random() * 2 - 1).normalize();
distance = FLOATING_POINT_EPSILON;
} else {
normal.scale(1f / distance);
}
// Calculate the target distance and penetration depth
target_distance = a.getRadius() + b.getRadius() + ENEMY_SEPARATION_GAP;
penetration = target_distance - distance;
// Resolve penetration by adjusting the positions of both enemies
if (penetration > COLLISION_SLOP) {
correction = (penetration - COLLISION_SLOP) * POSITION_BIAS_FACTOR * dt_scale;
a.setPos(
a.getCenterX() + normal.x * correction * 0.5f,
a.getCenterY() + normal.y * correction * 0.5f);
b.setPos(
b.getCenterX() - normal.x * correction * 0.5f,
b.getCenterY() - normal.y * correction * 0.5f);
}
// Skip if either enemy is in a knockback state
if (a.isKnockedBack() || b.isKnockedBack())
continue;
// Calculate the relative velocity between the two enemies
rel_vel = TMP_REL;
rel_vel.set(
b.getXVelocity() - a.getXVelocity(),
b.getYVelocity() - a.getYVelocity());
// Calculate the velocity along the collision normal
vel_along_normal = rel_vel.dot(normal);
// Skip if the enemies are moving away from each other
if (vel_along_normal > 0)
continue;
// Calculate the impulse scalar based on restitution
restitution = COLLISION_RESTITUTION;
impulse_scalar = -(1.0f + restitution) * vel_along_normal;
impulse_scalar /= 2.0f;
impulse_scalar *= dt_scale;
// Apply the impulse to both enemies
impulse = TMP_IMPULSE.set(normal.x, normal.y).scale(impulse_scalar);
// Calculate the friction impulse
tangent = TMP_TANGENT.set(-normal.y, normal.x);
vel_along_tangent = rel_vel.dot(tangent);
friction_impulse = -vel_along_tangent * COLLISION_FRICTION * impulse_scalar;
friction_vec = TMP_FRICTION.set(tangent.x, tangent.y).scale(friction_impulse);
a.setVelocity(
a.getXVelocity() - impulse.x - friction_vec.x,
a.getYVelocity() - impulse.y - friction_vec.y);
b.setVelocity(
b.getXVelocity() + impulse.x + friction_vec.x,
b.getYVelocity() + impulse.y + friction_vec.y);
}
}
}
public static void resolveAngelAngelCollisions(List<Angel> angels, float dt_scale, SpatialHashGrid<Entity> grid) {
Angel a = null;
float searchRad = 0f;
Entity ent = null;
Angel b = null;
int i = 0;
java.util.Iterator<Entity> qIt;
Vector normal;
float distance;
float target_distance;
float penetration;
float correction;
Vector rel_vel;
float vel_along_normal;
float restitution;
float impulse_scalar;
Vector impulse;
Vector tangent;
float vel_along_tangent;
float friction_impulse;
Vector friction_vec;
float a_speed_sq = 0f;
float b_speed_sq = 0f;
boolean a_moving_fast = false;
for (i = 0; i < angels.size(); i++) {
a = angels.get(i);
searchRad = a.getRadius() * 2f + ENEMY_SEPARATION_GAP;
qIt = grid.queryNearby((float) a.getCenterX(), (float) a.getCenterY(), searchRad).iterator();
while (qIt.hasNext()) {
ent = qIt.next();
if (!(ent instanceof Angel))
continue;
b = (Angel) ent;
if (a == b)
continue;
a_speed_sq = a.getXVelocity() * a.getXVelocity() + a.getYVelocity() * a.getYVelocity();
b_speed_sq = b.getXVelocity() * b.getXVelocity() + b.getYVelocity() * b.getYVelocity();
a_moving_fast = a_speed_sq > 0.25f;
if (!a_moving_fast && !(b_speed_sq > 0.25f))
continue;
// Skip if the angels' circles do not intersect
if (!circleIntersection(a, b))
continue;
// Calculate the collision normal vector
normal = TMP_NORMAL;
normal.set(
(float) (a.getCenterX() - b.getCenterX()),
(float) (a.getCenterY() - b.getCenterY()));
distance = normal.length();
// Handle cases where the distance is too small to avoid division by zero
if (distance < FLOATING_POINT_EPSILON) {
normal.set((float) Math.random() * 2 - 1, (float) Math.random() * 2 - 1).normalize();
distance = FLOATING_POINT_EPSILON;
} else {
normal.scale(1f / distance);
}
// Calculate the target distance and penetration depth
target_distance = a.getRadius() + b.getRadius() + ENEMY_SEPARATION_GAP;
penetration = target_distance - distance;
// Resolve penetration by adjusting the positions of both angels
if (penetration > COLLISION_SLOP) {
correction = (penetration - COLLISION_SLOP) * POSITION_BIAS_FACTOR * dt_scale;
a.setPos(
a.getCenterX() + normal.x * correction * 0.5f,
a.getCenterY() + normal.y * correction * 0.5f);
b.setPos(
b.getCenterX() - normal.x * correction * 0.5f,
b.getCenterY() - normal.y * correction * 0.5f);
}
// Calculate the relative velocity between the two angels
rel_vel = TMP_REL;
rel_vel.set(
b.getXVelocity() - a.getXVelocity(),
b.getYVelocity() - a.getYVelocity());
// Calculate the velocity along the collision normal
vel_along_normal = rel_vel.dot(normal);
// Skip if the angels are moving away from each other
if (vel_along_normal > 0)
continue;
// Calculate the impulse scalar based on restitution
restitution = COLLISION_RESTITUTION;
impulse_scalar = -(1.0f + restitution) * vel_along_normal;
impulse_scalar /= 2.0f;
impulse_scalar *= dt_scale;
// Apply the impulse to both angels
impulse = TMP_IMPULSE.set(normal.x, normal.y).scale(impulse_scalar);
// Calculate the friction impulse
tangent = TMP_TANGENT.set(-normal.y, normal.x);
vel_along_tangent = rel_vel.dot(tangent);
friction_impulse = -vel_along_tangent * COLLISION_FRICTION * impulse_scalar;
friction_vec = TMP_FRICTION.set(tangent.x, tangent.y).scale(friction_impulse);
a.setVelocity(
a.getXVelocity() - impulse.x - friction_vec.x,
a.getYVelocity() - impulse.y - friction_vec.y);
b.setVelocity(
b.getXVelocity() + impulse.x + friction_vec.x,
b.getYVelocity() + impulse.y + friction_vec.y);
}
}
}
// Checks if two circular entities intersect
public static boolean circleIntersection(Entity a, Entity b) {
float dx;
float dy;
float radius_sum;
dx = (float) (b.getCenterX() - a.getCenterX());
dy = (float) (b.getCenterY() - a.getCenterY());
radius_sum = a.getRadius() + b.getRadius();
return dx * dx + dy * dy <= radius_sum * radius_sum;
}
// Expands a rectangle based on the velocity of an entity
public static void expandRectByVelocity(Rectangle rect, float vx, float vy) {
float speedSq;
float speed;
int expansion;
speedSq = vx * vx + vy * vy;
if (speedSq > CONTINUOUS_COLLISION_THRESHOLD_SQ) {
speed = (float) Math.sqrt(speedSq);
expansion = (int) (speed * 0.5f);
rect.grow(expansion, expansion);
}
}
}