Game Engine - Pt.5
Collision detection was added along with a Shootable object class.
New Classes
Shootable.java
package ceccs;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
public class Shootable extends Circle {
RunNGunApp app;
double x, y, vx, vy, size;
double health;
Shootable(RunNGunApp app){
this.app = app;
size = 10;
setRadius(size);
health = 2;
setFill(Color.CYAN);
app.motionPane.getChildren().add(this);
}
void setPosition(double x, double y){
this.x = x;
this.y = y;
updateGraphics();
}
void setVelocity(double vx, double vy){
this.vx = vx;
this.vy = vy;
}
void updatePhysics(){
x += vx;
y += vy;
checkCollision();
}
void checkCollision(){
for (int i = 0; i < app.projectiles.size(); i++) {
Projectile p = app.projectiles.get(i);
if(RunNGunApp.collisionCheckCircles(this, p)) {
//temporary do something cooler
size += 10;
p.destroy();
i--;
}
}
}
void updateGraphics(){
setLayoutX(x);
setLayoutY(y);
setRadius(size);
}
}
Class Modificaitons & Changes
RunNGunApp.java
...
//at top
Shootable testTarget;
...
//new method added at bottom for collision checks
public static boolean collisionCheckCircles(Circle c1, Circle c2){
double dx = c2.getLayoutX() - c1.getLayoutX();
double dy = c2.getLayoutY() - c1.getLayoutY();
double distSqr = dx*dx + dy*dy;
double radSum = c1.getRadius() + c2.getRadius();
double radSumSqr = radSum * radSum;
if(distSqr < radSumSqr) {
return true; //collision detected
} else {
return false;
}
}
GameTimer.java
...
//loops were added to the update methods
void updatePhysics(){
...
//at bottom - updates for test target
app.testTarget.updatePhysics();
}
void updateGraphics(){
...
//at bottom - updates for test target
app.testTarget.updateGraphics();
}
...
Projectile.java
//new method
void destroy(){
app.motionPane.getChildren().remove(this);
app.projectiles.remove(this);
}