So, I'm making a game where the player spawns and has to fight enemies that spawn on the edge of the screen. Enemies spawn in waves (after the last wave of enemies dies, the new enemies spawn), the amount of enemies spawning is based on the score (the more score, the more enemies). I am now having trouble with the spawning of the enemies (which is in a for loop), on the third wave of spawning, I get a NullPointerException when trying to find my player class' Axis to try and follow it.
This is the code for my world where I spawn my enemies:
and here is the code for my Enemies:
Any help would be greatly appreciated!!
public static int highScore = 0; public static int score = 0; public Samurai s1; private BlueEnemy be1; private GreenEnemy ge1; private RedEnemy re1; private int blueSpawn = 0; private int redSpawn = 0; private int greenSpawn = 0; private boolean spawned = false; int xr = Greenfoot.getRandomNumber(2); public GameWorld() { super(1280, 720, 1); Samurai s1 = new Samurai(); HealthBar hb = new HealthBar(s1); this.addObject(s1,640,360); this.addObject(hb,140,60); be1 = new BlueEnemy(s1); ge1 = new GreenEnemy(s1); re1 = new RedEnemy(s1); if (score == 0) { for (int i = 0; i<2; i++) { this.addObject(be1,xr*1280,Greenfoot.getRandomNumber(720)); be1 = new BlueEnemy(s1); } } } public void act() { showText("Score: " + score,640,600); showText("High Score: " + highScore,640,540); if(GameWorld.score > GameWorld.highScore) { GameWorld.highScore = GameWorld.score; } spawnEnemy(); if (spawned == true) { checkDead(); } } public void spawnEnemy() { if (spawned == false && score != 0 && score != 1) { blueSpawn = score/2; redSpawn = score/2; greenSpawn = score/2; for (int i = 0; i<blueSpawn; i++) { this.addObject(be1,xr*1280,Greenfoot.getRandomNumber(720)); be1 = new BlueEnemy(s1); } for (int i = 0; i<redSpawn; i++) { this.addObject(re1,xr*1280,Greenfoot.getRandomNumber(720)); re1 = new RedEnemy(s1); } for (int i = 0; i<greenSpawn; i++) { this.addObject(ge1,xr*1280,Greenfoot.getRandomNumber(720)); ge1 = new GreenEnemy(s1); } spawned = true; } } public void checkDead() { if (getObjects(Enemy.class).isEmpty()) { spawned = false; } }
public class BlueEnemy extends Enemy { private Samurai s1; public BlueEnemy(Samurai S) { s1 = S; } public void act() { follow(); } private void follow() { if (this.getY() < s1.getY()+1 && this.getY() < s1.getY()-1) { setLocation(getX(), getY()+3); direction = 0; } else if (this.getX() > s1.getX()+1 && this.getX() > s1.getX()-1) { setLocation(getX()-3, getY()); direction = 3; } else if (this.getY() > s1.getY()+1 && this.getY() > s1.getY()-1) { setLocation(getX(), getY()-3); direction = 1; } else if (this.getX() < s1.getX()+1 && this.getX() < s1.getX()-1) { setLocation(getX()+3, getY()); direction = 2; } }