Jump to content
  • Advertisement
Sign in to follow this  
chtorr113

2D shooting cannon in Java errors

This topic is 1218 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys,

I'm new to java and I was trying to create a simple "game" in which you can shoot with a cannon.

I'm getting a lot of errors (java.lang.NullPointerException) and I can't figure out why

 

Here's the code

// Main Class

package Game.pkg0;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Game extends JPanel implements MouseListener, MouseMotionListener {
    
    static final int S_WIDTH = 600;
    static final int S_HEIGHT = 450;
    static final Dimension dimension = new Dimension(S_WIDTH, S_HEIGHT);
    static final int GRAVITY = 0;
    static final double ATTR = 1;
    static final double KSPEED = 1;
    final static int CX = -75;
    final static int CY = S_HEIGHT;
    final static int CW = Math.abs(CX * 2);
    final static int CH = 15;
    static double angle;
    static Vector direction;
    static long lastTime = System.nanoTime();
    static int elapsed;
    
    private Cannon cannon = new Cannon();
    private MissileSystem system = new MissileSystem();

    public Game() {
        
        JPanel panel = new JPanel();
        setSize(dimension);
        setPreferredSize(dimension);
        setVisible(true);
        setFocusable(true);
        addMouseListener(this);
        addMouseMotionListener(this);
                
    }
    
    @Override
    public void paint(Graphics g){
        
        Graphics2D g2 = (Graphics2D) g;
        
        g2.setColor(Color.BLACK);
        g2.fillRect(0, 0, S_WIDTH + 20, S_HEIGHT + 20);

        elapsed = (int) (System.nanoTime() - lastTime);       
        lastTime = System.nanoTime();
        
        system.draw(g2);
        cannon.draw(g2);
        
        repaint();
        
    }
    
    public static void main(String[] args) {
        
        Game game = new Game();        
        JFrame frame = new JFrame("CANNON GAME");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(dimension);
        frame.add(game);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.pack();
        
    }

    @Override
    public void mouseClicked(MouseEvent me) {
        
        system.add();
        
    }

    @Override
    public void mousePressed(MouseEvent me) {
    }

    @Override
    public void mouseReleased(MouseEvent me) {
    }

    @Override
    public void mouseEntered(MouseEvent me) {
    }

    @Override
    public void mouseExited(MouseEvent me) {
    }

    @Override
    public void mouseDragged(MouseEvent me) {
    }

    @Override
    public void mouseMoved(MouseEvent me) {
        
        int midX = CX + CW / 2,
            midY = CY + CH / 2,
            a = me.getX() - midX,
            b = midY - me.getY();
        double c = (double) Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
        angle = - Math.asin(b / c);
        direction = new Vector(a, b);
        
    }
    
}

// Entity Class

package Game.pkg0;

import java.awt.Color;
import java.awt.Graphics2D;

public abstract class Entity {

    private Vector position;
    private int w, h;
    private Color color;

    abstract void draw(Graphics2D g2);

    public Vector getPosition() {
        return position;
    }

    public void setPosition(Vector position) {
        this.position = position;
    }
    
    public double getX() {
        return position.getX();
    }

    public void setX(int x) {
        position.setX(x);
    }
    
    public double getY() {
        return position.getY();
    }

    public void setY(int y) {
        position.setY(y);
    }

    public int getW() {
        return w;
    }

    public void setW(int w) {
        this.w = w;
    }

    public int getH() {
        return h;
    }

    public void setH(int h) {
        this.h = h;
    }

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }
        
}

// Cannon Class

package Game.pkg0;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Cannon extends Entity{
    
    private final Rectangle shape = new Rectangle(Game.CX, Game.CY, Game.CW, Game.CH);

    public Cannon() {
    }

    @Override
    void draw(Graphics2D g2) {
        
        g2.setColor(Color.WHITE);
        g2.rotate(Game.angle, shape.getCenterX(), shape.getCenterY());
        g2.fill(shape);
        
    }
 
}

// MissileSystem Class

package Game.pkg0;

import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;

public class MissileSystem extends Entity{
    
    private List<Missile> missiles = new ArrayList<>();

    public MissileSystem() {
        
        System.out.println("Creato");
        
    }
    
    public void add(){
        
        double speed = Game.KSPEED * (double) Math.sqrt(Math.pow(Game.direction.getX(), 2) + Math.pow(Game.direction.getY(), 2));
        missiles.add(new Missile(speed, Game.angle));
        
    }
    
    @Override
    void draw(Graphics2D g2) {
        
        for(int k = 0; k < missiles.size(); k++){
            
            missiles.get(k).draw(g2);
            if((missiles.get(k).getX() > Game.S_WIDTH) || (missiles.get(k).getY() > Game.S_HEIGHT))
                missiles.remove(k);
            
        }
        
    }
    
}

// Missile Class

package Game.pkg0;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Missile extends Entity{
    
    private final static int WIDTH = 25;
    private final static int HEIGHT = 5;
    private Rectangle shape = new Rectangle((int) getX(), (int) getY(), getW(), getH());
    private Vector velocity = new Vector(0, 0);
    private final double speed;
    private double angle;

    public Missile(double speed, double angle) {
        
        setPos(Game.CX, Game.CY); 
        setW(WIDTH);
        setH(HEIGHT);
        angle = Math.toRadians(angle);
        this.speed = speed;
        velocity = new Vector(speed * Math.cos(angle), speed * Math.sin(angle));
                
    }
    
    private void update(){
        
        velocity.setX(velocity.getX() - velocity.getX() * Game.ATTR);
        velocity.setY(velocity.getY() - Game.GRAVITY);
        setPos((int) getX() + Game.elapsed * (int) velocity.getX(), (int) getY() + Game.elapsed * (int) velocity.getY());
        angle = Math.asin(velocity.getY() / velocity.getX());
        
    }
    
    private void setPos(int x, int y){
        
        super.setPosition(new Vector(x, y));
        shape.x = x;
        shape.y = y;
        
    }
    
    @Override
    void draw(Graphics2D g2) {
         
        update();
        g2.setColor(Color.RED);
        g2.rotate(angle, shape.getCenterX(), shape.getCenterY());
        g2.fill(shape);
        
    }

    public Vector getVelocity() {
        return velocity;
    }

    public void setVelocity(Vector velocity) {
        this.velocity = velocity;
    }
    
}

// Vector Class


package Game.pkg0;

public class Vector {
    
    private double x = 0, y = 0;

    public Vector() {
    }
        
    public Vector(double x, double y) {
        this.x = x;
        this.y = y;
    }
    
    public void add(Vector vector){
        
        this.x += vector.x;
        this.y += vector.y;
        
    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }
    
}

And here are the errors I get

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at Game.pkg0.Entity.getX(Entity.java:28)
	at Game.pkg0.Missile.<init>(Missile.java:16)
	at Game.pkg0.MissileSystem.add(MissileSystem.java:25)
	at Game.pkg0.Game.mouseClicked(Game.java:85)
	at java.awt.Component.processMouseEvent(Component.java:6528)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
	at java.awt.Component.processEvent(Component.java:6290)
	at java.awt.Container.processEvent(Container.java:2234)
	at java.awt.Component.dispatchEventImpl(Component.java:4881)
	at java.awt.Container.dispatchEventImpl(Container.java:2292)
	at java.awt.Component.dispatchEvent(Component.java:4703)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4542)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
	at java.awt.Container.dispatchEventImpl(Container.java:2278)
	at java.awt.Window.dispatchEventImpl(Window.java:2750)
	at java.awt.Component.dispatchEvent(Component.java:4703)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
	at java.awt.EventQueue.access$500(EventQueue.java:97)
	at java.awt.EventQueue$3.run(EventQueue.java:709)
	at java.awt.EventQueue$3.run(EventQueue.java:703)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
	at java.awt.EventQueue$4.run(EventQueue.java:731)
	at java.awt.EventQueue$4.run(EventQueue.java:729)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

I attached the file if that can help better (made in NetBeans)

 

Sorry for bad English

Share this post


Link to post
Share on other sites
Advertisement

Why don't you just look inside the file on top of the stacktrace on the line listed there?

That clearly tells you Entity.getX, line 28 is causing the NPE. Only thing done there is making a method call on the position, which you must have forgotten to create.

Thats probably because you did not add a contructor which uses the new operator to create one.

Edited by wintertime

Share this post


Link to post
Share on other sites
    private Rectangle shape = new Rectangle((int) getX(), (int) getY(), getW(), getH());
This is calling functions of the Missile class' parent (Entity) which has not been properly constructed at that point.

Share this post


Link to post
Share on other sites
    private Rectangle shape = new Rectangle((int) getX(), (int) getY(), getW(), getH());
This is calling functions of the Missile class' parent (Entity) which has not been properly constructed at that point.

 

I put "0, 0" instead of "(int) getX(), (int) getY()".

Now I don't get errors but the code doesn't work anyway, I'll work around that on my own.

Thank you!

Share this post


Link to post
Share on other sites
I would suggest to define a constructor for Entity and call this constructor (super) in the Constructor of Missile. Afterwards you can call the functions. That means you can define the Rectangle instance in the constructor of Missile using the functions GetX, GetY, GetW and GetH

Share this post


Link to post
Share on other sites

( This code has a little bit of an issue with spaghetti going on, which can make the code hard to read and debug )

 

 The error is a null pointer that was returned by ....

Game.pkg0.Entity.getX(Entity.java:28)

going to that class, we have this ...

public double getX() {
        return position.getX(); } 

tracing that back, we get

private Vector position;

This Vector object is not initiated whenever the Entity object is created - and thus is in a NULL state until it is set.

 

 You need to learn how to 'set' class objects and class verables whenever an object is created, using constructors [ LINK ]

Edited by Code Fox

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!