I'm trying to create a simple Space Invaders game in JavaFX. This is my first time so I have no idea how you properly do this. I'm trying to add collision detection, to remove a sprite if it's hit by a bullet.
All my sprites are rectangles with an imagePattern.
The enemies are 60 x 43, the bullet is 4 x 8. My idea was to just check if the bullet is within the translateX of a sprite, and if its the same Translate Y - its height. But for some reason this code doesn't work. It causes an Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
when a bullet hits a sprite.
if (game.lookup("#bullet") != null) {
for (Sprite sprite : enemies) {
if (game.lookup("#bullet").getTranslateX() >= sprite.getTranslateX() && game.lookup("#bullet").getTranslateX() <= sprite.getTranslateX() + 60 && game.lookup("#bullet").getTranslateY() == sprite.getTranslateY() - 43) {
System.out.println("HIT!");
}
}
}
Some help would be much appreciated.
Note: I am sure this is not the most efficient way to go about it, but its the only idea I have.
The stack trace:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at Main$1.handle(Main.java:131)
at javafx.graphics/javafx.animation.AnimationTimer$AnimationTimerReceiver.lambda$handle$0(AnimationTimer.java:57)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/javafx.animation.AnimationTimer$AnimationTimerReceiver.handle(AnimationTimer.java:56)
at javafx.graphics/com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(AbstractMasterTimer.java:357)
at javafx.graphics/com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(AbstractMasterTimer.java:267)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:514)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:498)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:491)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:319)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
at java.base/java.lang.Thread.run(Thread.java:844)