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

2012/9/6

Error at setLocation(mouse.getX(), mouse.getY());

Reck Reck

2012/9/6

#
I am making a game where you shoot down birds. I've made an actor that acts as a Crosshair, following the mouse around. This is the code which is generating the error (setLocation is line 18):
MouseInfo mouse = Greenfoot.getMouseInfo();
setLocation(mouse.getX(), mouse.getY());
And the error code:
java.lang.NullPointerException
	at Crosshair.act(Crosshair.java:18)
	at greenfoot.core.Simulation.actActor(Simulation.java:565)
	at greenfoot.core.Simulation.runOneLoop(Simulation.java:523)
	at greenfoot.core.Simulation.runContent(Simulation.java:213)
	at greenfoot.core.Simulation.run(Simulation.java:203)
Zamoht Zamoht

2012/9/6

#
Use:
if(Greenfoot.mouseMoved(null)) {
            MouseInfo mouse = Greenfoot.getMouseInfo();
            setLocation(mouse.getX(), mouse.getY());
        }
from the balloons scenario.
Reck Reck

2012/9/6

#
That worked out, thank you :-)
davmac davmac

2012/9/6

#
Better to use this:
    MouseInfo mouse = Greenfoot.getMouseInfo();
    if (mouse != null) {
        setLocation(mouse.getX(), mouse.getY());
    }
(Because getMouseInfo() can in some cases still return null even if mouseMoved() returns true).
You need to login to post a reply.