This site requires JavaScript, please enable it in your browser!
Greenfoot back
boilboil
boilboil wrote ...

2017/4/23

Null Pointer Exception Strikes Again!

boilboil boilboil

2017/4/23

#
So I have this code, for a game I'm making. Whenever I run the game (not compile), it throws a null pointer exception. Do you know how I can fix this?
public class PADDLE extends Game
{
    /**
     * Act - do whatever the PADDLE wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    int dx;
    
    public void act(){
        
        int x = Greenfoot.getMouseInfo().getX();
        
        if ( x > 0 ) {
            setLocation( getX() + dx , getY() );
        }
    }
}
Super_Hippo Super_Hippo

2017/4/23

#
You have to make sure the 'getMouseInfo' didn't return null.
MouseInfo mouse = Greenfoot.getMouseInfo();
if (mouse != null)
{
    x = mouse.getX();
    if (x>0) setLocation(getX()+dx, getY());
}
boilboil boilboil

2017/4/24

#
Alright, I see my problem. Because the mouse itself was null. Great. But the problem now is that the object does not actually move to my mouse. It just sits there. Do you know why it doesn't seem to move?
danpost danpost

2017/4/24

#
boilboil wrote...
the problem now is that the object does not actually move to my mouse. It just sits there. Do you know why it doesn't seem to move?
Does 'dx' have a value (other than zero, its default value) set to it? What value should it be? When should it have a value? Looks to me like you are trying to have the Paddle object move horizontally toward the mouse at a given rate (which probably is the value that 'dx' should be set to). If that is the case, then you do not need a condition on moving -- just on the setting of 'x', the x-coordinate of the mouse:
MouseInfo mouse = Greenfoot.getMouseInfo();
if (mouse != null) x = mouse.getX();
move(dx*(int)Math.signum(x-getX()));
The last line determines where the mouse is with respect to the actor, left (-1), right (1) or at (0); then multiplies that direction by the speed to move.
You need to login to post a reply.