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

2016/9/14

Mouse Motion

dimpap5555 dimpap5555

2016/9/14

#
Hello, I was trying to make a game with an actor a rocket. The thing i want to do is to make for ever when the left click of the mouse is pressed the actor's Y must change to the Mouse's Y Here's the code: public class Rocket extends Actor { /** * Act - do whatever the Rocket wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ MouseInfo mouse = Greenfoot.getMouseInfo(); public void act() { if(Greenfoot.mouseClicked(this)) { setLocation(mouse.getX(),getY()); } }
Super_Hippo Super_Hippo

2016/9/14

#
Try this out:
public void act()
{
    if(Greenfoot.mouseClicked(null)) //null = any click, not only on this object
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        setLocation(getX(), mouse.getY()); //set y to mouse y, not x
    }
}
I prefer using 'mousePressed' though. Then it triggers when the button is pressed down and not after it was clicked and released. I am not 100 % sure if clicking outside of the world would trigger the condition... If you get a Nullpointer Exception, use the following in front of line 6:
if (mouse != null)
danpost danpost

2016/9/14

#
The placement of this line:
 MouseInfo mouse = Greenfoot.getMouseInfo();
is such that it executes only once, during the creation of the Actor object -- even before the actor is placed into the world. Obviously, you want it to execute once for every act cycle executed; therefore, it needs to be placed within the act method, if you needed that line at all (which you do not). The condition of the 'if' statement, as coded, will detect (or be true when the) mouse clicks while the mouse is upon this actor. This is not what you are wanting, however; you want any mouse click anywhere within the world. Therefore, 'this' should be 'null' for the argument of 'mouseClicked'. If the condition is true, then 'Greenfoot.getMouseInfo' will not return 'null'; therefore, you can just code it as follows:
public void act()
{
    if (Greenfoot.mouseClicked(null))
    {
        setLocation(getX(), Greenfoot.getMouseInfo().getY());
    }
}
You need to login to post a reply.