Related
My game is a shooting game for school. I need help on the collision between my bullet and my enemy. I have placed the bullet class with my player but for some reason it keeps on passing through it and not disappearing. The first example below shows the weapon class which is for the bullet and the one underneath that is the main.
class Weapons{
PImage bullet;
int speed;
int imageSize = 20;
float x = 20;
float y = 20;
float m;
int damage = 5;
int[] src = new int[2];
float[] dest = new float[2];
Weapons(int x, int y){
speed = 12;
dest[0] = mouseX;
dest[1] = mouseY;
src[0] = x;
src[1] = y;
m = (dest[1]-src[1]) / (dest[0]-src[0]);
this.x = x;
this.y = y;
bullet = loadImage("bullet.png");
bullet.resize(imageSize,imageSize);
}
boolean shooting(){
image(bullet, x, y); // if attack is true then renfer the image
x += speed;
y = (m * (x - dest[0])) + dest[1];
return (x > width || y > height);
}
boolean crash(Enemy enemies) {
//// return the result of checking if the plane has crashed into the bird
return abs(this.x-enemies.x) < bullet.width && abs(this.y - enemies.y) < bullet.height;
}
}
Maincharacter MC;
Goal G;
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Weapons> bullets = new ArrayList<>();
final int Playing = 0;
final int Finish = 1;
int gameMode = Playing;
//Enemy[] enemies = new Enemy[10];
PImage background; // creating background
int bgX = 0;
void setup(){
size(800,500);
MC = new Maincharacter(100,3);
//E1 = new Enemy();
G = new Goal(100,20);
background = loadImage("Battleground1.png");
background.resize(width*2,height); //set image to be same size as the canvas
for(int i = 0; i<2; i++){ // i represent how many enemy I want.
enemies.add(new Enemy((int)random(200,850), (int)random(0, height- 150) ) );
}
//for(int i=0 ; i < enemies.length ; i++){
//enemies[i] = new Enemy(); }
}
void draw(){
if(gameMode == Playing){
background();
MC.display();
G.display();
for(Enemy E : enemies){
E.update();
if (MC.crash(E)){
gameMode = Finish;
}
}
for(Weapons W: bullets){
W.update();
if(enemies.crash(W)){ // doesnt exist
gameMode = Finish;
}
}
// for(int i=0 ; i < enemies.length ; i++){
//enemies[i].update(); }
}}
void keyPressed(){
// creating the movemnt for my main charcter
MC.move();
if (keyCode == RIGHT || keyCode == 68 ){
MC.x += 10;
} else if (keyCode == UP || keyCode == 87) {
MC.y -=10;
} else if (keyCode == LEFT || keyCode == 65){
MC.x -= 10;
} else if(keyCode == DOWN || keyCode == 83 ){
MC.y += 10;
} else if (keyCode == 32) { // space bar
MC.attack_function(); // call attack function to create bullet object
}// make an attack
}
void mousePressed(){ // when mouse is pressed call attack function to create bullet object
MC.attack_function();
}
void background(){
//scrolling background image
image(background, bgX, height/2); //draw image to fill the canvas
//draw image again off the right of the canvas
image(background, bgX+background.width, height/2);
bgX -= 4;
if(bgX == -background.width ) //if first image completely off the canvas
{
bgX=0; //reset back to initial value background
}
}
What I want is to have bullet colliding with the enemies and then disappearing.
You are trying to call the method enemies.crash(W) but enemies is some collection of Enemy instances. Enemy does not provide the method crash as well.
You have to loop for each of your enemies all of your weapons and call the method crash on the Weapon instance giving the current enemy, something like:
for (Enemy enemy: enemies){
enemy.update();
if (mainCharacter.crash(enemy)) {
gameMode = Finish;
}
for (Weapons weapon: bullets) {
weapon.update();
if (weapon.crash(enemy)) {
gameMode = Finish;
// TODO: are you sure that killing an enemy finishes the game?
}
}
}
(Please note that I used mainCharacter instead of MC here for better readability.)
Hi this is my code the code should work like after clicking the new spawned cirlce another one should apear and after cliking the new one another one should spawn but it has some problem , for example i dont know what type of logic i should write for it? should i write
recursion if yes then how?
float xpaikka =random(640);
float ypaikka =random(640) ;
int value_y = 0 ;
int value_x = 0 ;
void setup(){
size(640,640);
frameRate(500);
background(34,45,323);
}
void draw(){
ellipse(xpaikka,ypaikka,60,60);
float randomi_x = random(630);
float randomi_y = random(630);
var d= dist(mouseX,mouseY,randomi_x,ypaikka);
if (d < 30 && value_x != 0){
ellipse(randomi_x,randomi_y,60,60);
value_x = 0;
}
}
void mousePressed() {
if (value_x == 0) {
value_x = mouseX;
print("mouseX",value_x);
} else {
value_x = 0;
}
}
void mousePressed2() {
if (value_y == 0) {
value_y = mouseY;
print("mouseY",mouseY);
} else {
value_y = 0;
}
}
Use an PVector to represent a the center point of the circle
PVector centerPoint = new PVector(random(640), random(640));
When the mouse button is pressed, calculate the distance from the mouse to the center of the circle. If the distance is less than the radius of the circle, create a new random center point:
PVector mousePoint = new PVector(mouseX, mouseY);
if (mousePoint.dist(centerPoint) <= 30.0) {
centerPoint = new PVector(random(640), random(640));
}
Complete example:
PVector centerPoint = new PVector(random(640), random(640));
void setup() {
size(640, 640);
}
void draw() {
background(34, 45, 323);
ellipse(centerPoint.x, centerPoint.y, 60, 60);
}
void mousePressed() {
PVector mousePoint = new PVector(mouseX, mouseY);
if (mousePoint.dist(centerPoint) <= 30.0) {
centerPoint = new PVector(random(640), random(640));
}
}
I am programming a game with libGDX. The protagonist can shoot at some flying enemies.
Heres my problem:
I don't know how I can handle multiple shots at the same time. Here is my code:
private Image backgroundImage = new Image(backgroundTexture);
private Stage levelStage = new Stage(), menuStage = new Stage();
private Table menuTable = new Table();
private Skin menuSkin = Manager.menuSkin;
private OrthographicCamera camera;
private SpriteBatch batch;
private Rectangle farmer, ufo;
private Array<Rectangle> lasers;
private boolean ufoMovementLeft = true;
private boolean leftArrow = false;
private boolean rightArrow = false;
private float laserMovement[] = new float[100];
private int ufoLife = 15;
#Override
public void show() {
levelStage.addActor(backgroundImage);
Gdx.input.setInputProcessor(levelStage);
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
farmer = new Rectangle();
farmer.x = 480 / 2 - 56 / 2; farmer.y = 80;
farmer.width = 55; farmer.height = 140;
ufo = new Rectangle();
ufo.x = 500 / 2; ufo.y = 600;
ufo.width = 160; ufo.height = 70;
lasers = new Array<Rectangle>();
}
public void spawnLaser() {
Rectangle laser = new Rectangle();
if(Gdx.input.justTouched()) {
lasers.add(laser);
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
laserMovement[lasers.size] = touchPos.x;
camera.unproject(touchPos);
laser.x = farmer.x + 50; laser.y = 110;
laser.width = 25; laser.height = 20;
}
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
levelStage.act();
levelStage.draw();
batch.setProjectionMatrix(levelStage.getCamera().combined);
batch.begin();
movement();
if(leftArrow) {if(farmer.x >= 50) farmer.x -= 2;
batch.draw(farmerLeftTexture, farmer.x, farmer.y);}
else if(rightArrow) {if(farmer.x <= 370) farmer.x += 2;
batch.draw(farmerRightTexture, farmer.x, farmer.y);}
else batch.draw(farmerBackTexture, farmer.x, farmer.y);
if(ufoMovementLeft) {ufo.x -= 1;
if(ufo.x < 50) ufoMovementLeft = false; }
else {ufo.x += 1; if(ufo.x > 300) ufoMovementLeft = true ; }
batch.draw(ufoTexture, ufo.x, ufo.y);
if(Gdx.input.justTouched()) spawnLaser();
Iterator<Rectangle> iter = lasers.iterator();
while(iter.hasNext()) {
Rectangle laser = iter.next();
laser.y += 300 * Gdx.graphics.getDeltaTime();
laser.x += (laserMovement[lasers.size] - farmer.x + farmer.x * 0.25) * 2 * Gdx.graphics.getDeltaTime();
if(laser.overlaps(ufo)){iter.remove(); ufoLife -= 1;}
if(laser.y + 64 > 550) iter.remove();
}
for(Rectangle laser: lasers) {
batch.draw(laserTexture, laser.x, laser.y);
}
The problem at this point is that the shots are handled "as if they were one". If the player shoots in a different direction than the other shots before, every bullet that is on the screen at the moment changes its direction.
I just have no idea how to solve this problem, so every help is appreciated :).
Cheers, Joshflux
EDIT: I edited the code, and here are some screenshots:
The first one shows to shots fired to the left side, but in the second one you can see that after i fired two shots to the right side, the first two shots also start to move to the right.
I am trying to make a scrolling game - where the player (in space) is constantly at the center of the screen. As he moves left right up and down, a background spritesheet will randomly generate coloured stars - so the moving stars will be an indication of which direction the player is moving in.
The problem I am now having is that the stars are not displaying when I run the game. Each tile is supposed to be 32x32, each containing at least one star, with the 'nostars' tile being empty. When I run the game, I just get a black screen.
RandomLevel.java:
protected void generateLevel() {
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
bgtiles[x + y * width] = random.nextInt(4);
}
}
}
Level.java
public void render(int xScroll, int yScroll, Screen screen) {
screen.setOffset(xScroll, yScroll);
int x0 = xScroll >> 5;
int x1 = (xScroll + screen.width + 32) >> 5;
int y0 = yScroll >> 5;
int y1 = (yScroll + screen.height + 32) >> 5;
for(int y = y0; y < y1; y++) {
for(int x = x0; x < x1; x++) {
getTile(x, y).render(x, y, screen);
}
}
}
public Tile getTile(int x, int y) {
if(x < 0 || y < 0 || x >= width || y >= height) return Tile.nostars;
if(bgtiles[x + y * width] == 0) return Tile.stars1;
if(bgtiles[x + y * width] == 1) return Tile.stars2;
if(bgtiles[x + y * width] == 2) return Tile.stars3;
if(bgtiles[x + y * width] == 3) return Tile.stars4;
else return Tile.nostars;
}
SpaceTile.java
public class SpaceTile extends Tile {
public SpaceTile(Sprite sprite) {
super(sprite);
}
public void render(int x, int y, Screen screen) {
screen.renderTile(x << 5, y << 5, this);
}
}
SpriteSheet.java
public static SpriteSheet bgtiles = new SpriteSheet("/textures/bgsheet.png", 256);
Sprite.java
public static Sprite spaceSprite = new Sprite(32, 0, 0, SpriteSheet.bgtiles);
public static Sprite stars1 = new Sprite(64, 0, 0, SpriteSheet.bgtiles);
public static Sprite stars2 = new Sprite(96, 0, 0, SpriteSheet.bgtiles);
public static Sprite stars3 = new Sprite(128, 0, 0, SpriteSheet.bgtiles);
public static Sprite stars4 = new Sprite(160, 0, 0, SpriteSheet.bgtiles);
Tile.java
public class Tile {
public int x, y;
public Sprite sprite;
public static Tile nostars = new SpaceTile(Sprite.spaceSprite);
public static Tile stars1 = new SpaceTile(Sprite.stars1);
public static Tile stars2 = new SpaceTile(Sprite.stars2);
public static Tile stars3 = new SpaceTile(Sprite.stars3);
public static Tile stars4 = new SpaceTile(Sprite.stars4);
public Tile(Sprite sprite) {
this.sprite = sprite;
}
public void render(int x, int y, Screen screen) {
}
public boolean solid() {
return false;
}
}
Game.java
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;
public static String title = "Game";
private Thread thread;
private JFrame frame;
private Keyboard key;
private Level level;
private boolean running = false;
private Screen screen;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
screen = new Screen(width, height);
frame = new JFrame();
key = new Keyboard();
level = new RandomLevel(64, 64);
addKeyListener(key);
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
double ns = 1000000000.0 / 60.0;
double delta = 0;
int frames = 0;
int updates = 0;
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
requestFocus();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
update();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer >= 1000) {
timer += 1000;
frame.setTitle(title + " | " + updates + " ups, " + frames + " fps");
frames = 0;
updates = 0;
}
}
stop();
}
int x, y = 0;
public void update() {
key.update();
if(key.up == true) y--;
if(key.down == true) y++;
if(key.left == true) x--;
if(key.right == true) x++;
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.clear();
level.render(x, y, screen);
for(int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle(Game.title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
bgsheet.png
https://i.imgur.com/0yUKql2.png?1
In the generatelevel() I am only trying it out with the first 4 tiles, not all of the 64 tiles.
When I run the game, I expect to see 4 different stars scattered everywhere but instead I just get a black screen.
Thanks in advance for any help !
From the code posted, it appears that you forgot to load the background into image. I placed this code into a new public method called loadAssets(). Call this before you call game.start().
public void loadAssets() {
try {
image = ImageIO.read(new URL("https://i.imgur.com/0yUKql2.png?1"));
} catch (MalformedURLException ex) {
Logger.getLogger(GameTwo.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GameTwo.class.getName()).log(Level.SEVERE, null, ex);
}
}
I also commented out the following code in render().
screen.clear();
level.render(x, y, screen);
for(int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
So from what I understand, you make a call to draw using BufferedImage image, however you have not actually loaded your image data into the variable image. I will provide a code snippet that you may need to tailor a bit
File imageFile = new File("/path/to/image.file");
BufferedImage image = ImageIO.read(imageFile);
There may be a faster way as you have already called
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
But as you can probably imagine, that doesn't actually connect you image variable to an image file. My best guess is that the code I provided will work, but honestly you'll have to try it.
Happy coding and leave a comment if you have any questions!
The problem turned out to be simply that I had the wrong co-ordinates for each sprite. Sorry for wasting your time and thanks for the help anyway!
public static Sprite spaceSprite = new Sprite(32, 0, 0, SpriteSheet.bgtiles);
public static Sprite stars1 = new Sprite(32, 1, 0, SpriteSheet.bgtiles);
public static Sprite stars2 = new Sprite(32, 2, 0, SpriteSheet.bgtiles);
public static Sprite stars3 = new Sprite(32, 3, 0, SpriteSheet.bgtiles);
public static Sprite stars4 = new Sprite(32, 4, 0, SpriteSheet.bgtiles);
I am having some serious problems with my Asteroid game. I'm trying to call my Game.java run() method in my main method in Asteroid.java but I keep getting the same error:
Exception in thread "main" java.lang.NullPointerException
at asteroids.Asteroids.main(Asteroids.java:15)
Java Result: 1
Can someone help me figure out why this is happening?
here is my code:
Asteroids.java
package asteroids;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.io.IOException;
#SuppressWarnings("serial")
public class Asteroids {
Game game = null;
public static void main(String[] args){
new Asteroids ().game.run ();
}
}
//NEW Game.java//
package asteroids;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
//#SuppressWarnings("serial")
public class Game extends Applet implements Runnable, KeyListener {
//timing variables
Thread thread;
long startTime, endTime, framePeriod;
//graphics variables
Image img;
Dimension dim;
int width, height;
Graphics g;
//text items
int level, lives, score;
SpaceShip ship;
boolean shipCollision, shipExplode;
//ArrayList to hold asteroids
ArrayList<Asteroid> asteroids = new ArrayList<>();
int numOfAsteroids = 1;
//ArrayList to hold the lasers
ArrayList<Laser> lasers = new ArrayList<>();
final double rateOfFire = 10; //limits rate of fire
double rateOfFireRemaining; //decrements rate of fire
//ArrayList to hold explosion particles
ArrayList<AsteroidExplosion> explodingLines = new ArrayList<>();
//ArrayList to hold ship explosions
ArrayList<ShipExplosion> shipExplosion = new ArrayList<>();
public void Game ()
{
init();
}
public void init() {
resize(900,700); //set size of the applet
dim = getSize(); //get dimension of the applet
width = dim.width;
height = dim.height;
framePeriod = 25; //set refresh rate
addKeyListener(this); //to get commands from keyboard
setFocusable(true);
ship = new SpaceShip(width/2, height/2, 0, .15, .5, .15, .98); //add ship to game
shipCollision = false;
shipExplode = false;
level = numOfAsteroids;
lives = 3;
addAsteroids();
img = createImage(width, height); //create an off-screen image for double-buffering
g = img.getGraphics(); //assign the off-screen image
thread = new Thread(this);
thread.start();
}
#Override
public void paint(Graphics gfx) {
Graphics2D g2d = (Graphics2D) g;
//give the graphics smooth edges
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height); //add a black background
//add text for lives, score, and level
g2d.setColor(Color.WHITE);
g2d.drawString("Level : " + level, 10, 690);
g2d.drawString("Lives : " + lives, 110, 690);
g2d.drawString("Score : " + score, 210, 690);
for(Asteroid a: asteroids) { //draw asteroids
a.draw(g2d);
}
for(Laser l : lasers) { //draw lasers
l.draw(g2d);
}
for(AsteroidExplosion e : explodingLines) {
e.draw(g2d);
}
for(ShipExplosion ex : shipExplosion)
ex.draw(g2d);
ship.draw(g2d); //draw ship
if(shipCollision) {
shipExplosion.add(new ShipExplosion(ship.getX(), ship.getY(), 10, 10));
ship.setX(width/2);
ship.setY(height/2);
shipCollision = false;
lives--;
}
gfx.drawImage(img, 0, 0, this); //draw the off-screen image (double-buffering) onto the applet
}
#Override
public void update(Graphics gfx) {
paint(gfx); //gets rid of white flickering
}
#Override
public void run(){
for( ; ; ) {
startTime = System.currentTimeMillis(); //timestamp
ship.move(width, height); //ship movement
for(Asteroid a : asteroids) { //asteroid movement
a.move(width, height);
}
for(Laser l : lasers) { //laser movement
l.move(width, height);
}
for(int i = 0 ; i<lasers.size() ; i++) { //laser removal
if(!lasers.get(i).getActive())
lasers.remove(i);
}
for(AsteroidExplosion e : explodingLines) { //asteroid explosion floating lines movement
e.move();
}
for(int i = 0 ; i<explodingLines.size(); i++) { //asteroid explosion floating lines removal
if(explodingLines.get(i).getLifeLeft() <= 0)
explodingLines.remove(i);
}
for(ShipExplosion ex : shipExplosion){ //ship explosion expansion
ex.expand();
}
for(int i = 0 ; i<shipExplosion.size() ; i++) {
if(shipExplosion.get(i).getLifeLeft() <= 0)
shipExplosion.remove(i);
}
rateOfFireRemaining--;
collisionCheck();
if(asteroids.isEmpty()) {
numOfAsteroids++;
addAsteroids();
level = numOfAsteroids;
}
repaint();
try {
endTime = System.currentTimeMillis(); //new timestamp
if(framePeriod - (endTime-startTime) > 0) //if there is time left over after repaint, then sleep
Thread.sleep(framePeriod - (endTime - startTime)); //for whatever is remaining in framePeriod
} catch(InterruptedException e) {}
}
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
//fires laser
if(key == KeyEvent.VK_SPACE) {
if(rateOfFireRemaining <= 0 ) {
lasers.add(ship.fire());
rateOfFireRemaining = rateOfFire;
}
}
if(key == KeyEvent.VK_UP)
ship.setAccelerating(true);
if(key == KeyEvent.VK_RIGHT)
ship.setTurningRight(true);
if(key == KeyEvent.VK_LEFT)
ship.setTurningLeft(true);
if(key == KeyEvent.VK_DOWN)
ship.setDecelerating(true);
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP)
ship.setAccelerating(false);
if(key == KeyEvent.VK_RIGHT)
ship.setTurningRight(false);
if(key == KeyEvent.VK_LEFT)
ship.setTurningLeft(false);
if(key == KeyEvent.VK_DOWN)
ship.setDecelerating(false);
}
#Override
public void keyTyped(KeyEvent e) {
}
public void addAsteroids() {
int numAsteroidsLeft = numOfAsteroids;
int size;
for(int i=0 ; i<numOfAsteroids ; i++) { //add asteroids to game
//randomize starting position
int asteroidX = (int)(Math.random() * width) + 1;
int asteroidY = (int)(Math.random() * height) + 1;
//randomize speed and direction
double xVelocity = Math.random() + 1; //horizontal velocity
double yVelocity = Math.random() + 1; //vertical velocity
//used starting direction
int xDirection = (int)(Math.random() * 2);
int yDirection = (int)(Math.random() * 2);
//randomize horizontal direction
if (xDirection == 1)
xVelocity *= (-1);
//randomize vertical direction
if (yDirection == 1)
yVelocity *= (-1);
//if there are more then four asteroids, any new ones are MEGA asteroids
if(numAsteroidsLeft > 4) {
size = 2;
} else { size = 1;
}
asteroids.add(new Asteroid(size, asteroidX, asteroidY, 0, .1, xVelocity, yVelocity));
numAsteroidsLeft--;
//Make sure that no asteroids can appear right on top of the ship
//get center of recently created asteroid and ship and check the distance between them
Point2D asteroidCenter = asteroids.get(i).getCenter();
Point2D shipCenter = ship.getCenter();
double distanceBetween = asteroidCenter.distance(shipCenter);
//if asteroid center is within 80 pixels of ship's center, remove it from the ArrayList and rebuild it
if(distanceBetween <= 80) {
asteroids.remove(i);
i--;
numAsteroidsLeft++;
}
}
}
public void collisionCheck() {
//cycle through active asteroids checking for collisions
for(int i = 0 ; i < asteroids.size() ; i++) {
Asteroid a = asteroids.get(i);
Point2D aCenter = a.getCenter();
//check for collisions between lasers and asteroids
for(int j = 0 ; j < lasers.size() ; j++) {
Laser l = lasers.get(j);
Point2D lCenter = l.getCenter();
double distanceBetween = aCenter.distance(lCenter);
if(distanceBetween <= (a.getRadius() + l.getRadius())) {
//split larger asteroids into smaller ones, remove smaller asteroids from screen
if(a.getRadius() >= 60) {
for(int k = 0 ; k < 3 ; k++)
explodingLines.add(a.explode());
split(i);
score += 200;
} else if(a.getRadius() >= 30){
for(int k = 0 ; k < 3 ; k++)
explodingLines.add(a.explode());
split(i);
score += 100;
} else {
for(int k = 0 ; k < 3 ; k++)
explodingLines.add(a.explode());
asteroids.remove(i);
score += 50;
}
lasers.remove(j); //remove laser from screen
}
}
//check for collisions between ship and asteroid
Point2D sCenter = ship.getCenter();
double distanceBetween = aCenter.distance(sCenter);
if(distanceBetween <= (a.getRadius() + ship.getRadius())) {
shipCollision = true;
shipExplode = true;
}
}
}
public void split(int i) {
Asteroid a = asteroids.get(i);
double bigAsteroidX = a.getX();
double bigAsteroidY = a.getY();
int size = (a.getSize() / 2);
asteroids.remove(i);
for(int j = 0 ; j<2 ; j++) {
//randomize speed and direction
double xVelocity = Math.random() + 1; //horizontal velocity
double yVelocity = Math.random() + 1; //vertical velocity
//used randomize starting direction
int xDirection = (int)(Math.random() * 2);
int yDirection = (int)(Math.random() * 2);
//randomize horizontal direction
if (xDirection == 1)
xVelocity *= (-1);
//randomize vertical direction
if (yDirection == 1)
yVelocity *= (-1);
asteroids.add(new Asteroid(size, bigAsteroidX, bigAsteroidY, 0, .1, xVelocity, yVelocity));
}
}
}
//Edit Update//
Okay I tried a lot of stuff and discovered that even though the game works when I debug Game.java and it doesn't work when I run it through Asteroids.java. I found that img = createIimg = createImage(width, height); and g = img.getGraphics(); are returning null and that GraphicsEnvironment.isHeadless() is returning true. How should I change my to fix this issue?
Error
Exception in thread "main" java.lang.NullPointerException
at asteroids.Game.init(Game.java:67)
at asteroids.Game.Game(Game.java:45)
at asteroids.Asteroids.main(Asteroids.java:15)
Java Result: 1
You have the var "game" null, and you tried to call the method "run" on this var (game.run); obviously if "game" is null, you can't get the method, and throws nullpointer exception.
Game game=new Game();
that's all you need. Your final code is:
Game game = new Game();//<----- here is the change
public static void main(String[] args){
new Asteroids ().game.run ();
}
This thing is null.
new Asteroids ().game
That's why you get this NullPointerException when you call run on it.
Game game = null;
public static void main(String[] args){
new Asteroids ().game.run ();
}
The prgram is running from the main method. game is null.
Maybe you should have
Game game = new Game(); // instead of null
Try it may be help
Game game = null;
public static void main(String[] args){
If( Asteroids ().game != null ){
new Asteroids ().game.run ();
}
}