6

OK what I am trying to do here is create a game where the object/ball is controlled by clicking on the object with the mouse, pulling back the mouse (the distance the mouse is pulled back will determine the velocity of the object) and on releasing the button the object will move (it's angle of movement will also be determined by the angle the mouse was pulled back)

Now as far as I can tell the 'math' at least should just about work, unfortunately I haven't been able to test that out as I'm getting the following error.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Snail.moveUp(Snail.java:35)
at Snail.chill(Snail.java:20)
at Level.mouseReleased(Level.java:120)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

From what i understand this means that i may have declared something which has a null value, but this is confusing me as i have done printouts of all my variables and all are giving values.

I then assumed that perhaps i am telling the object to move before the value has been declared, but i can't figure out why that would be happening.

My Code is as follows.

import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.event.MouseInputListener;

@SuppressWarnings("serial")
public class Level extends JPanel implements ActionListener, MouseInputListener{

Timer time;
private Image i;
private Graphics doubleG;
Snail s, s2;

boolean canJump;
int sx2;
int sy2;
int sx3;
int sy3;
double clickX;
double clickY;
double relX;
double relY;
double angle;
double speed;
double distance;

double scalex;
double scaley;
double velocityx = 1;
double velocityy = 1;

public Level(){

    s = new Snail();
    setFocusable(true);

    addMouseListener(this);
    addMouseMotionListener(this);
    //s2 = new Snail(250, 250);
    time = new Timer(17, this);
    time.start();   
}

@Override //double buffer
    public void update(Graphics g) {
        super.update(g);
            if(i == null){
                i = createImage(this.getSize().width, this.getSize().height);
                doubleG = i.getGraphics();
            }

            doubleG.setColor(getBackground());
            doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);

            doubleG.setColor(getForeground());
            paint(doubleG);

            g.drawImage(i, 0, 0, this);
    }

public void actionPerformed(ActionEvent e){
    s.update(this);
    //s2.update(this);
    repaint();


}

public void paintComponent (Graphics g) {   super.paintComponent(g); 
    s.paint(g);
    //s2.paint(g);

}

@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent ep) {
    clickX = ep.getX();
    clickY = ep.getY();
}

@Override
public void mouseReleased(MouseEvent er) {
    relX = er.getX();
    relY = er.getY();
    angle = Math.toRadians(Math.atan2(clickY - relY, clickX - relX));

    distance = Math.hypot(relX-clickX, relY-clickY);
    speed = distance/8;

    scalex = Math.cos(angle);
    scaley = Math.sin(angle);
    velocityx = speed * scalex;
    velocityy = speed * scaley;

    if (speed > 20){
        speed = 20;
    }

    if (canJump) {s.moveUp();

    }

}

@Override
public void mouseDragged(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseMoved(MouseEvent em) {
    sx2 = s.x - s.radius;
    sy2 = s.y + s.radius;
    sx3 = s.x + s.radius;
    sy3 = s.y - s.radius;

    if (em.getX() >= sx2 && em.getX() <= sx3 && em.getY() >= sy3 && em.getY() <= sy2){
        canJump = true;
    }else{
        canJump = false;
    }
    System.out.println("Click   X " + clickX + " Click   Y " + clickY);
    System.out.println("Release X " + relX + " Release Y " + relY);
    System.out.println("angle" + angle);
    System.out.println("distance" + distance);
    System.out.println("velx " + velocityx);
    System.out.println("vely " + velocityy);
    System.out.println(scalex);
    System.out.println(scaley);
    System.out.println(" ");

}

}

This would be the second class to which the error seems to be occurring, i am calling on an instance variable from the class above.

import java.awt.Color;
import java.awt.Graphics;


public class Snail {

Level l;
private double gravity = 10;
private double energyloss = 0.6;
private double xFriction = .95;
private double dt = .2;
int x = 0;
int y = 0;
double dx = 0;
double dy = 0;
int radius = 30;


public void chill(){
    moveUp();
}

public Snail() {
    // TODO Auto-generated constructor stub
}

public Snail(int i, int j) {
    // TODO Auto-generated constructor stub
    x = i;
    y = j;
}

public void moveUp() {
        dx = dx + l.velocityx;
        dy = dy + l.velocityy;
} 

public void update(Level l){

    if (x + dx > l.getWidth() -radius){
        x = l.getWidth() -radius;
        dx = - dx;
    }else if( x + dx < 0 +radius){
        x = 0+radius;
        dx = -dx;
    }
    else{
        x += dx;
    }

    if(y == l.getHeight()-radius)
        dx *= xFriction;
    if (Math.abs(dx) < .9){
        dx = 0;
    }

    if (y > l.getHeight() -radius){
        y = l.getHeight() -radius;
        dy *= energyloss;
        dy = - dy;
    }else{
        //velocity formula
        dy = dy + gravity *dt;
        //position formula
        y += dy*dt + .5*gravity*dt*dt;
    }

}

public void paint(Graphics g){
    g.setColor(Color.RED);
    g.fillOval(x-radius, y-radius, radius*2, radius*2);
}

}

Finally the class that initialises the level.

import javax.swing.JFrame;

public class Frame {


public static void main(String[] args){
    JFrame frame = new JFrame("Hard as Snails");
    frame.add(new Level());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1280,720);
    frame.setVisible(true);

}

}

Could anyone help me on what i am doing wrong here, I am quite new too this level of coding so please explain as if talking to an idiot. Many thanks for your time!

Phil
  • 61
  • 1
  • 1
  • 3
  • 2
    `so please explain as if talking to an idiot.` ok ;) `this means that i may have declared something which has a null value` - by default all objects are null when declared unless you assign a value to them. `Level l;` - you declared it, but didn't assign a value to it. – camickr Mar 22 '13 at 19:55

1 Answers1

8

Your Level l object seems to be null. As you havent initialized it and you are trying to use it in moveUp() method throwing NullPointerException.

You should initialized it as follows.

 Level l = new Level();
  1. You should assign values double x = 1.0;. I can see double x = 1; everywhere which could give you unexpected results.
Smit
  • 4,685
  • 1
  • 24
  • 28
  • I tried as you suggested but changing Level l; to Level l = new Level(); Gives me a new exception handler, and the app fails to load. – Phil Mar 22 '13 at 20:06
  • 2
    @phile I dont know what new exception its causing. I just took a look at your code and suggested what I saw wrong. However what its the error its throwing. – Smit Mar 22 '13 at 20:10
  • Sorry, here is the new exception: – Phil Mar 22 '13 at 20:45
  • Iv also changed all those values to doubles, thanks for the tip. Unfortunately I get the same error. Iv also added the final class file above, where my level is initialised originally in 'main'- frame.add(new Level()); is this incorrect? thanks – Phil Mar 22 '13 at 20:56
  • @Phil I cant tell you where is and what is going wrong. Better you post new question with problems you are facing. Dont post all of your code just a part where it s throwing exception and stacktrace. – Smit Mar 22 '13 at 21:35
  • 2
    @Phil don't worry too much about those double's. An int gets upcasted to a double without loss of precision nor any other trouble. Many languages suffer from those type conversion but not Java (at least in this case). – Guillaume Polet Mar 22 '13 at 23:17
  • Ok thanks guys, i'll keep looking. – Phil Mar 23 '13 at 21:01