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

2013/11/15

Player shooting while mouse is pressed

jordan32 jordan32

2013/11/15

#
The player shoots continuously while the mouse is clicked and moving but once I stop moving the mouse the player stops shooting. Is there a way to have the player always shooting while the mouse is clicked?
public void shoot()
    {
       MouseInfo mouseInfo = Greenfoot.getMouseInfo();
       if (mouseInfo != null)
       {
            if (mouseInfo.getButton() == 1)
            {
               getWorld().addObject(new Bullet(), getX(), getY());
            }
       }
    }
danpost danpost

2013/11/16

#
'getMouseInfo' will return 'null' unless there is a change in the state of the mouse (it is moved or a button changes state from up to down or down to up. You will probably need to add an instance boolean field to track the state of mouse button one:
// add instance field
private boolean mseBtn1;
// the 'shoot' method
public void shoot()
{
    MouseInfo mouseInfo = Greenfoot.getMouseInfo();
    if (mouseInfo == null || mouseInfo.getButton() != 1) return; // no change
    if (!mseBtn1 && Greenfoot.mousePressed(null)) mseBtn1 = true; // button one pressed
    if (mseBtn1 && Greenfoot.mouseClicked(null)) mseBtn1 = false; // button one released
    if (mseBtn1) getWorld().addObject(new Bullet(), getX(), getY()); // firing bullet
}
I did not test this and I know that sometimes it is very difficult to get exactly the results you want when it comes to the mouse; but, it should be close to what you want. Line 9 may also need to check for 'mouseDragEnded':
if (mseBtn1 && (Greenfoot.mouseClicked(null) || Greenfoot.mouseDragEnded(null))) mseBtn1 = false;
jordan32 jordan32

2013/11/17

#
Thanks for the help but it didn't work.
KevinWelch2001 KevinWelch2001

2013/11/17

#
it worked good for my game I did change some code though
jordan32 jordan32

2013/11/17

#
What did you change?
You need to login to post a reply.