Results 1 to 3 of 3
  1. #1
    hamChan is offline Member
    Join Date
    Jun 2013
    Posts
    18
    Rep Power
    0

    Default How to get rid of null exception?

    Hi, my friends and I are developing a simple 2D game for better understanding.

    I'm only trying to add a function that a player can shoot arrows to a direction the player is facing at.
    For example, if he is facing left and when he shoots an arrow then, it should go left.
    Same to facing right.

    The modules are provided by them and I confirmed that a player can shoot arrow. but after I modified some it starts not working..
    What I was thinking is that
    1: when a LEFT key is pressed, parse it to faceDir() in Player class and set a "faceDirection" with the value.
    2: move() in Arrow class is called when a player presses attack key. so inside move(), check which direction the player is facing at.
    3: shoot an arrow towards either left or right according to the player's direction checked in move().

    and I get a "NullPointerException" error when I run it. Would you plz help me out?

    Java Code:
    ----------------------------- Arrow Class
    import java.awt.Color;
    import java.awt.Graphics;
    
    import java.awt.Point;
    
    /**
     *
     */
    public class Arrow {
    	private static final int SPEED = 6; // the arrow's speed
    	public static final int WIDTH = 16;
    	public static final int HEIGHT = 16;
    
    	// arrow storage where arrows are invisible
    	private static final Point STORAGE = new Point(-40, -40);
    	// direction instance variable
    	private static final int LEFT = 0;
    	private static final int RIGHT = 1;
    
    	private double x; // arrow's position (x-coordinate)
    	private double y; // arrow's position (y-coordinate)
    	private double width; // arrow's width
    	private double height; // arrow's height
    
    	private MainPanel panel; // reference to the MainPpanel
    	private Player player;
    	
    	
    	// --------------------------------------------- Constructors
    
    	// Initialise arrows' position at STORAGE (invisible)
    	// @param panel -> reference to the Main Panel
    	public Arrow(MainPanel panel) {
    		this.x = STORAGE.x;
    		this.y = STORAGE.y;
    		this.panel = panel;
    
    	}
    
    	// Move the arrow
    	public void move() {
    		if (isInStorage()) { // if the shot are in the storage
    			return; // do nothing
    		}
    
    		  if (player.getDirection() == LEFT){
    		  		 x -= SPEED;
    		  } else if (player.getDirection() == RIGHT){ 
    		  	x += SPEED;
    		  }
    
    		//x -= SPEED; // when the above codes are executed, disable this
    
    		// an arrow went outside the screen goes to the storage
    		if (x < 0 || x > panel.WIDTH) {
    			store();
    		}
    	}
    
    	// Draw the arrow
    	// @param g -> a draw object
    	public void draw(Graphics g) {
    		g.setColor(Color.RED);
    		g.fillRect((int) x, (int) y, WIDTH, HEIGHT);
    	}
    
    	// Set the arrow
    	// @param x, y -> x-coordinate, y-coordinate of the arrow
    	public void setPos(double x, double y) {
    		this.x = x;
    		this.y = y;
    	}
    
    	// Return the arrow's width
    	// @return width -> the width of the arrow
    	public double getWidth() {
    		return width;
    	}
    
    	// Return the arrow's height
    	// @return height -> the height of the arrow
    	public double getHeight() {
    		return height;
    	}
    
    	// Get the current position of the arrow.
    	// @return -> the current position
    	public Point getPos() {
    		return new Point((int) x, (int) y);
    	}
    
    	// Store all arrows in the storage.
    	public void store() {
    		x = STORAGE.x;
    		y = STORAGE.y;
    	}
    
    	// Judge whether the arrow is stored in the storage.
    	// @return -> if it is in the storage, return "true"
    	public boolean isInStorage() {
    		if (x == STORAGE.x && y == STORAGE.x)
    			return true;
    		return false;
    	}
    
    }
    
    
    ----------------------------- Player class
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Point;
    
    /**
     * 
     */
    public class Player{
      public static final int WIDTH = 32;
      public static final int HEIGHT = 32;
      private static final int SPEED = 6; // the player's movement speed
      
      private static final int LEFT = 0; // direction instance variable
      private static final int RIGHT = 1; // direction instance variable
      
      private double x; // the player's position (x-coordinate)
      private double y; // the player's position (y-coordinate)
    
      private double width; // player's width
      private double height; // player's height
      private int faceDirection; // direction the player is facing at
      
      // speed rate
      private double vx;
      private double vy; 
    
      public Player(double x, double y){
        this.x = x;
        this.y = y;
        
        vx = 0;
        vy = 0;
        faceDirection = RIGHT;
      }
    
      // Move the player in given commands.
      // @param dir -> direction to move the player
      public void move(int dir){
        if (dir == LEFT){
          vx = - SPEED;
        }else if (dir == RIGHT){
          vx = SPEED;
        }
      }
      
      // Change the player's direction according to given value
      public void faceDir(int dir){ // it seems that this returns a collect value when this is called in MainPanel class
        if (dir == LEFT){
          faceDirection = LEFT;
        } else if (dir == RIGHT){
          faceDirection = RIGHT;
        }
      }
    
      // Stop the player movement
      public void stop(){
        vx = 0;
      }
      
      // Update the player's conditions
      public void update(){
        x += vx;
        y += vy;
      }
      
      // Draw the player on a screen.
      // @param g -> a drawing object
      public void draw(Graphics g){
        g.setColor(Color.GREEN);
        g.fillRect((int) x, (int) y, WIDTH, HEIGHT);
      }
    
      // Return the player's face direction
      public int getDirection(){
        return faceDirection;
      }
      
      // Return the player's width
      // @return width -> the width of the player
      public double getWidth() {
        return width;
      }
    
      // Return the player's height
      // @return height -> the height of the player
      public double getHeight() {
        return height;
      }
    
      // Get the current position of the player.
      // @return -> the current position
      public Point getPos() {
        return new Point((int) x, (int) y);
      }
    }
    
    ----------------------------------- MainPanel class
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.Point;
    
    import javax.swing.JPanel;
    
    /**
     * 
     */
    public class MainPanel extends JPanel implements Runnable, KeyListener{
      // the panel size
      public static final int WIDTH = 700; // the width of a panel
      public static final int HEIGHT = 400; // the height of a panel
      
      // the direction instance variables
      private static final int LEFT = 0;
      private static final int RIGHT = 1;
      
      
      private Player player; // a player
      private Arrow attack; // attack
    
      // Key conditions (use these conditions to control a player)
      private boolean leftPressed = false;
      private boolean rightPressed = false;
      private boolean firePressed = false;
    
      private Thread gameLoop; // for a game loop thread
      
      public MainPanel(){
        // set the recommended panel size. (needs for pack())
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        
        // allow panel to receive key-enters
        setFocusable(true);
        
        player = new Player(0, HEIGHT - Player.HEIGHT);
        attack = new Arrow(this);
        
        // register the key-event listener
        addKeyListener(this);
        
        // game-loop starts
        gameLoop = new Thread(this);
        gameLoop.start();
      }
      
      private void move(){
        // move a player
        // when nothing is prssed, no movement
        if(leftPressed){
          player.faceDir(LEFT);
          player.move(LEFT);
        } else if(rightPressed){
          player.faceDir(RIGHT);
          player.move(RIGHT);
        } else {
          player.stop();
        }
      }
    
      // Loop the painting of a game and responding to key-enters.
      public void run(){
        while (true){
          move(); // move the player
          
          player.update(); // update the player's conditions
               
          
          if (firePressed) {
            if (attack.isInStorage()) {
              Point posX = player.getPos();
               attack.setPos(posX.x - player.getWidth()/8, posX.y);
            }
          }
          attack.move();
          repaint(); // repaint
          // Stop
          try{
            Thread.sleep(20);
          } catch (InterruptedException e){
            e.printStackTrace();
          }
        }
      }
      
      // Processe the components of painting.
      // @param g -> a drawing object
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        
        // set the black screen and paint in black.
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, getWidth(), getHeight());
        
        player.draw(g); // draw a player
        attack.draw(g); // draw attack
    
        g.setColor(Color.WHITE);
        g.drawString("the player is facing at", 510, 15); // showing player information
        g.drawString("0 <- Left :[ " + player.getDirection() + " ]: 1 -> Right", 500,30); // 0 means facing Left. 1 means facing Right
      }
      
      
      public void keyTyped(KeyEvent e){
      }
      
      // Change to a condition "Key-Pressed", when a key is presed.
      // @param e -> a key event
      public void keyPressed(KeyEvent e){
        int key = e.getKeyCode();
        
        if (key == KeyEvent.VK_A){
          leftPressed = true;
        }
        if (key == KeyEvent.VK_D){
          rightPressed = true;
        }
        if (key == KeyEvent.VK_SPACE){
          firePressed = true;
        }
      }
      
      // Change to a condition "Key-Released", when a key is released.
      // @param e -> a key event
      public void keyReleased(KeyEvent e){
        int key = e.getKeyCode();
        
        if (key == KeyEvent.VK_A){
          leftPressed = false;
        }
        if (key == KeyEvent.VK_D){
          rightPressed = false;
        }
        if (key == KeyEvent.VK_SPACE){
          firePressed = false;
        }
      }
      
    }
    
    ------------------------------- execution class
    import java.awt.Container;
    
    import javax.swing.JFrame;
    /**
     * This program computes the game.
     */
    public class Frog extends JFrame{
      public Frog(){
        setTitle("Jumping Frog"); // set a title
        setResizable(false);
        
        // create a main panel and add it to a frame
        MainPanel panel = new MainPanel();
        Container contentPane = getContentPane();
        contentPane.add(panel);
        pack();
      }
      
      public static void main(String[] args){
        Frog frame = new Frog();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
      }
    }

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: How to get rid of null exception?

    Quote Originally Posted by hamChan View Post
    I get a "NullPointerException" error when I run it. Would you plz help me out?
    The stack trace will tell you on which line some variable hadn't been assigned a value (or had explicitly been assigned to null).

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    hamChan is offline Member
    Join Date
    Jun 2013
    Posts
    18
    Rep Power
    0

    Default Re: How to get rid of null exception?

    Quote Originally Posted by DarrylBurke View Post
    The stack trace will tell you on which line some variable hadn't been assigned a value (or had explicitly been assigned to null).

    db
    Hi,
    I checked it and things I've done to fix it are ;

    ・Create a new method that accepts a parameter which sets direction in Arrow Class from void move() in MainPanel class.
    Java Code:
    // Set the arrow direction and return its direction
    	public int setDir(int dir){
    		if (dir == LEFT){
    			direction = LEFT;
    		} else if (dir == RIGHT){
    			direction = RIGHT;
    		}
    		return direction;
    	}
    ・Then, insert attack.setDir(LEFT); into
    Java Code:
    private void move(){
        // move a player
        // when nothing is prssed, no movement
        if(leftPressed){
          attack.setDir(LEFT);
          player.faceDir(LEFT);
          player.move(LEFT);
        } else if(rightPressed){
          attack.setDir(RIGHT);
          player.faceDir(RIGHT);
          player.move(RIGHT);
        } else {
          player.stop();
        }
      }
    to parse the data
    ・After the variable "direction" is assigned at setDir() in Arrow class, add conditions in move() in Arrow class like this
    Java Code:
    // Move the arrow
    	public void move() {
    		if (isInStorage()) { // if the shot are in the storage
    			return; // do nothing
    		}
    		if (direction == LEFT){
    			x -= SPEED;
    		} else if (direction == RIGHT){
    			x += SPEED;
    		}
    		//x -= SPEED; // when the above codes are executed, disable this
    		// an arrow went outside the screen goes to the storage
    		if (x < 0 || x > panel.WIDTH) {
    			store();
    		}
    	}
    I'm glad that now I can see an arrow being shot by a player based on the direction he is facing at.
    but something weird happens too.

    like when the player facing towards left and shot an arrow, it goes left. It is good. That's what I expected.
    but when the player faces right while the arrow is still within the screen, it starts moving towards right as if its coming back to the player.

    I know there must be something wrong with arrow direction but still not sure where I went wrong.

Similar Threads

  1. Null Pointer exception
    By leapinlizard in forum Spring
    Replies: 2
    Last Post: 10-19-2012, 09:35 AM
  2. null pointer exception help
    By captain_turkiye in forum New To Java
    Replies: 17
    Last Post: 12-04-2011, 12:27 AM
  3. Null Pointer exception (Again !!)
    By mobosecomin in forum New To Java
    Replies: 6
    Last Post: 03-29-2011, 05:04 PM
  4. Null pointer exception
    By Domo230 in forum New To Java
    Replies: 4
    Last Post: 02-28-2011, 10:21 AM
  5. null pointer exception
    By jyothi.priyanka in forum New To Java
    Replies: 12
    Last Post: 03-11-2009, 05:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •