(JavaFX) How do I check for collision between animated circles? - java

My assignment is to have a button for adding balls which appear at random location and direction. I'm having trouble checking for collision between the balls. The trouble is on line 123. Thanks!
import java.util.ArrayList;
import java.util.Scanner;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
class BallPane extends Pane {
private double radius = 10;
private ArrayList<Ball> list = new ArrayList();
private Timeline animation;
public BallPane() {
Scanner kb = new Scanner(System.in);
System.out.println("\nPlease press RIGHT and LEFT arrow keys to increase and decrease"
+ " the speed of the balls.");
animation = new Timeline(
new KeyFrame(Duration.millis(50), (ActionEvent e) -> {
moveBall();
}));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play(); // Start animation
}
public void addBall() {
Ball balls = new Ball(BallPane.this);
getChildren().add(balls.getCircle());
list.add(balls);
}
public void moveBall() {
double x, y, dx, dy;
// Check boundaries
Ball a;
for (int i = 0; i < list.size(); i++) {
a = list.get(i);
x = a.getCircle().getCenterX();
y = a.getCircle().getCenterY();
dx = a.getDirectionX() + (int) Math.random() * 100;
dy = a.getDirectionY() + (int) Math.random() * 100;
if (x < a.getCircle().getRadius()
|| x > getWidth() - a.getCircle().getRadius()) {
dx *= -1; // Change ball move direction
}
if (y < a.getCircle().getRadius()
|| y > getHeight() - a.getCircle().getRadius()) {
dy *= -1; // Change ball move direction
}
// Adjust ball position
x += dx;
y += dy;
a.setDirectionX(dx);
a.setDirectionY(dy);
a.getCircle().setCenterX(x);
a.getCircle().setCenterY(y);
// Ball b = list.get(i + 1);
}
//line 123
//also trying to use the distance formula to check the distance between two circles' center points
for (int i = 0; i < Timeline.INDEFINITE; i++) {
if (Math.sqrt(Math.pow(list.get(i).getCenterX()
- list.get(i + 1).getCenterX(), 2) + Math.pow(list.get(i).getCenterY()
- list.get(i + 1).getCenterY(), 2)) <= 2 * radius) {
list.get(i).getCircle();
getChildren().remove(i);
list.remove(i);
}
}
}
}//End of BallPane class.
Thanks for the help! It is mostly code Stack Overflow... why're you making me type this.asdl;kfj dsal;kf jldfjals ;kdjfldksajf l;askfj

try the following codes modified from Mailkov's original post by reversing the looping order
for (int i = list.size()-1; i >=1 ; i--)
{
for (int j=(i-1); j >=0; j--)
{
if (Math.sqrt(Math.pow(list.get(i).getCenterX() - list.get(j).getCenterX(), 2) +
Math.pow(list.get(i).getCenterY() - list.get(j).getCenterY(), 2)) <= 2 * radius )
{
list.get(i).getCircle();
getChildren().remove(i);
list.remove(i);
break; // I think we need to break out the for (j) loop here
}
}
}

try this:
ArrayList<Integer> ballexplode=new ArrayList<Integer>();
for (int i = 0; i < list.size()-1; i++) {
for (int j=i+1; j < list.size();j++){
if (Math.sqrt(Math.pow(list.get(i).getCenterX()
- list.get(j).getCenterX(), 2) + Math.pow(list.get(i).getCenterY()
- list.get(j).getCenterY(), 2)) <= 2 * radius) {
list.get(i).getCircle();
ballexplode.add(i);
ballexplode.add(j);
}
}
}
for (int i=ballexplode.size()-1;i>=0;i--){
getChildren().remove(ballexplode.get(i));
list.get(ballexplode.get(i)).getCircle();
}

Related

Java 2D Polygon - Polygon Collision Detection

Recently I have been using the Polygon class to create asteroids as well as bullets and a spaceship. I am currently trying to create the collision detection for the program however it appears that the collision detection only works around 1/5 of the time (no pattern appears as to why it works).
Here's the code..
Creating the Polygon:
void renderPoly() {
int j;
int s = sides;
double r, angle;
int x, y;
for (j = 0; j < s; j++) {
angle = 2 * Math.PI / s * j;
r = MIN_ROCK_SIZE + (int) (Math.random() * (MAX_ROCK_SIZE - MIN_ROCK_SIZE));
x = (int) (r * Math.cos(angle));
y = (int) (r * -Math.sin(angle));
cOM[0] += x;
cOM[1] += y;
pointData[j][0] = x;
pointData[j][1] = y;
}
cOM[0] /= asteroidShape.npoints;
cOM[1] /= asteroidShape.npoints;
for (int i = 0; i < asteroidShape.npoints; i++) {
pointData[i][0] += cOM[0];
pointData[i][1] += cOM[1];
}
}
rotating and moving the polygon:
void move() {
int x, y, i;
//change rotation
theta += rotVel;
//change x
asteroidData[0] += deltaX;
//change y
asteroidData[1] += deltaY;
for (i = 0; i < asteroidShape.npoints; i++) {
x = (int) (pointData[i][0] * Math.cos(theta) - pointData[i][1] * Math.sin(theta) );
y = (int) (pointData[i][0] * Math.sin(theta) + pointData[i][1] * Math.cos(theta) );
asteroidShape.xpoints[i] = x + asteroidData[0];
asteroidShape.ypoints[i] = y + asteroidData[1];
asteroidShape.invalidate();
}
}
check if touching bullet:
boolean hitBullet(Bullet b) {
this.asteroidShape.invalidate();
for (int i = 0; i < b.bulletShape.npoints; i++)
if (this.asteroidShape.contains(b.bulletShape.xpoints[i], b.bulletShape.ypoints[i]) )
return true;
for (int j = 0; j < this.asteroidShape.npoints; j++)
if (b.bulletShape.contains(this.asteroidShape.xpoints[j], this.asteroidShape.ypoints[j]) )
return true;
return false;
}
(the ship method is the same except the constructor requires a ship object)
as well as the loop that calls it in the 'game' class:
for (int i = 0; i < aArray.length-1; i++) {
if (aArray[i] != null) {
for (int j = 0; j < bArray.length-1; j++) {
if (bArray[j] != null) {
if (aArray[i].hitBullet(bArray[j])) {
aArray[i] = null;
bArray[j] = null;
i = aArray.length-1;
j = bArray.length-1;
}
}
else {
i = aArray.length-1;
j = bArray.length-1;
}
}
}
else {
i = aArray.length-1;
}
}
I have been looking around at alternative solutions such as the Separating Axis Theorem however I do have convex polygons at times and since this method (.contains()) already exists I would like to use it.
Any help would be appreciated, thanks!
The easy way to solve this that I've found is to convert Shapes (in your case Polygon(2D?)) into Areas. You can use Area.intersect(Area) to see if two Areas have collided

Determine if circles intersect

I am working on a project where I have to draw 20 circles with random starting points and random sizes. Then I have to determine if any of the circles intersect. If a circle intersects with another, I have to color that circle green. And if the circle does not intersect with another, the color needs to be red. I have all of the code... I think... but when I run it, I still get some circles that should be green, but are red instead. Here is my code. Any help will be greatly appreciated.
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Random;
import javax.swing.JFrame;
import java.awt.*;
public class IntersectingCircles extends JPanel
{
private int[] xAxis = new int [20]; // array to hold x axis points
private int[] yAxis = new int [20]; // array to hold y axis points
private int[] radius = new int [20]; // array to hold radius length
public static void main (String[] args)
{
JFrame frame = new JFrame("Random Circles");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new IntersectingCircles());
frame.pack();
frame.setVisible(true);
}
public IntersectingCircles()
{
setPreferredSize(new Dimension(1300, 800)); // set window size
Random random = new Random();
for (int i = 0; i < 20; i++)
{
xAxis[i] = random.nextInt(800) + 100;
yAxis[i] = random.nextInt(500) + 100;
radius[i] = random.nextInt(75) + 10;
}
}
public void paintComponent(Graphics g)
{
for (int i = 0; i < 20; i++)
{
int color = 0;
for (int h = 0; h < 20; h++)
{
if(i < h)
{
double x1 = 0, x2 = 0, y1 = 0, y2 = 0, d = 0;
x1 = (xAxis[i] + radius[i]);
y1 = (yAxis[i] + radius[i]);
x2 = (xAxis[h] + radius[h]);
y2 = (yAxis[h] + radius[h]);
d = (Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1)*(y2 - y1))));
if (d > radius[i] + radius[h] || d < (Math.abs(radius[i] - radius[h])))
{
color = 0;
}
else
{
color = 1;
break;
}
}
}
if (color == 0)
{
g.setColor(Color.RED);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
else
{
g.setColor(Color.GREEN);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
}
}
}
In the inside for loop, you are only comparing circles of i index with circles with h index, but only those with i < h, because of the condition:
for (int h = 0; h < 20; h++)
{
if(i < h)
{
...
So, instead you should compare every i circle with every h circle, except if they are the same. You want instead:
for (int h = 0; h < 20; h++)
{
if(i != h) //note the change here
{
...

2D elastic collision not working properly

I've have this code and the balls bounces around, but when I apply some gravity I want them to stay on top of each other. But instead they slowly fall through.
Screenshot
Here's my code.
for (int i = 0; i < balls.size(); i++) {
Ball curr = balls.get(i);
if (curr.getPos().getX() - curr.radius <= 0) {
curr.getVel().mul(-0.9, 1);
curr.getPos().set(curr.radius, curr.getPos().getY());
} else if (curr.getPos().getX() + curr.radius >= WIDTH) {
curr.getVel().mul(-0.9, 1);
curr.getPos().set(WIDTH - curr.radius, curr.getPos().getY());
}
if (curr.getPos().getY() - curr.radius <= 0) {
curr.getVel().mul(1, -0.9);
curr.getPos().set(curr.getPos().getX(), curr.radius);
} else if (curr.getPos().getY() + curr.radius >= HEIGHT) {
curr.getVel().mul(1, -0.9);
curr.getPos().set(curr.getPos().getX(), HEIGHT - curr.radius);
}
for (int j = 0; j < balls.size(); j++) {
if (j == i) continue;
Ball other = balls.get(j);
double xDist = curr.getPos().getX() - other.getPos().getX();
double yDist = curr.getPos().getY() - other.getPos().getY();
double distance = xDist * xDist + yDist * yDist;
if (distance <= (curr.radius + other.radius) * (curr.radius + other.radius)) {
double xVel = other.getVel().getX() - curr.getVel().getX();
double yVel = other.getVel().getY() - curr.getVel().getY();
double dot = xDist * xVel + yDist * yVel;
if (dot > 0) {
double colScale = dot / distance;
double xCol = xDist * colScale;
double yCol = yDist * colScale;
double mass = curr.mass + other.mass;
double weightCurr = 2 * other.mass / mass;
double weightOther = 2 * curr.mass / mass;
curr.getVel().add(weightCurr * xCol, weightCurr * yCol);
other.getVel().sub(weightOther * xCol, weightOther * yCol);
curr.getPos().add(curr.getVel().mul(DMP));
other.getPos().sub(other.getVel().mul(DMP));
}
}
}
}
Thanks!
A line should be inserted after this one:
for (int j = 0; j < balls.size(); j++) {
if( j == i ) continue;
Otherwise each ball is balling with itself.
Another potential source of error is the way balls are bounced against the four walls and each other: The first ball is wall-checked and then bounces against all others, and only then are all others wall-checked.
for (int i = 0; i < balls.size(); i++) {
Ball curr = balls.get(i);
// wall checks
} // wall-check done!
for (int i = 0; i < balls.size(); i++) {
Ball curr = balls.get(i);
for (int j = 0; j < balls.size(); j++) {
if( j == i ) continue;
// ball - ball check ...
}
}
Also, if ball 1 passes the check with ball 2, but ball 2 is then pushed away by ball 3 into the radius of ball 1, overlaps may occur. Not sure how to cope with this: repeat ball-ball until no corrections are necessary?

i need to program this code with arraylist

anything i do seems to break down my code into unusable rubbish. Note that it is also a mess... but at least it does work almost properly.
Here are some details:
it's sort of a particle system but with images. koffer stands for bag and it has to be a sort of eplosion of rotating bags that get slightly bigger or smaller for the depth effect and they fade away in time and after leaving the screen it should be deleted.
For now i got half of the bags that explode to turn random ways and half of the bags don't do that. They all fade but don't get deleted after leaving the screen. there is no slight resize yet. But most of all i have to use an arraylist() and don't know how to implement that.
here is my code:
Main Class BagEplode:
PImage coffre;
float life = 255;
int i = 0;
Ball [] balls = new Ball [200];
void setup(){
size (600,600,P3D);
noStroke();
smooth();
coffre = loadImage("coffre.png");
for (i = 0; i < balls.length; i ++)
{
balls[i] = new Ball();
}
}
void draw()
{
clear();
life -= 2.5;
for (int i = 0; i < balls.length; i++)
{
if(i <= 4)
{
balls[i].kleur();
image(coffre, balls[i].x, balls[i].y);
tint(255, life);
balls[i].update();
}
//else
//{
//}
}
}
and i got the Class Ball:
class Ball
{
public void kleur(){
}
float x = width/2;
float y = 601;
float vX = random(1,4);
float vY = random(-9,-5);
float sizeX = 0 ;
float sizeY = 0 ;
float draaiHoek = 0;
float angle = random(-3,3);
public void update(){
x += vX ;
y += vY ;
vY += 0.125;
sizeX = 64 ;
sizeY = 64 ;
draaiHoek -=angle;
imageMode(CENTER);
pushMatrix();
translate(x,y);
rotate((radians(draaiHoek)));
image(coffre, 0, 0);
imageMode(CORNER);
popMatrix();
//if (x > width || x < 0 || y > height || y < 0)
//{
//}
}
}
Thanx for helping me in advance. I hope i really can get some pointers.
From my understanding, you need to replace balls array of type- Ball with an ArrayList of type Ball
import java.util.ArrayList;
public class Ball {
PImage coffre;
float life = 255;
int i = 0;
//Ball [] balls = new Ball [200];
ArrayList<Ball> balls= new ArrayList<Ball>();
void setup(){
size (600,600,P3D);
noStroke();
smooth();
coffre = loadImage("coffre.png");
/* for (i = 0; i < balls.length; i ++)
{
balls[i] = new Ball();
}
*/
for(int i=0;i<balls.size();i++)
{
balls.add(new Ball());
}
}
void draw()
{
clear();
life -= 2.5;
/* for (int i = 0; i < balls.length; i++)
{
if(i <= 4)
{
balls[i].kleur();
image(coffre, balls[i].x, balls[i].y);
tint(255, life);
balls[i].update();
}
*/
for (int i = 0; i < balls.size(); i++)
{
if(i <= 4)
{
balls.get(i).kleur();
image(coffre, balls.get(i).x, balls.get(i).y);
tint(255, life);
balls.get(i).update();
}
//else
//{
//}
}
}
}

Asteroid game NullPointerException error

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 ();
}
}

Categories