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

2015/4/27

Help Needed! Button clicking

TheGoldenBucket TheGoldenBucket

2015/4/27

#
Hey everyone! I need a bit of help with my code to click buttons and change worlds. Here is what I have: it does not work correctly
import greenfoot.*;

/**
 * Write a description of class HydraButton here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class HydraButton extends Actor
{
    public int button;
    /**
     * Act - do whatever the HydraButton wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if(mouse!=null)
        {
            button = mouse.getButton();
            if(button == 1 && Greenfoot.mouseClicked(null))
            {
                if(mouse.getY() == getY() && mouse.getX() == getX())
                {
                    World hydraboss = new HydraBoss();
                    Greenfoot.setWorld(hydraboss);
                }
            }
        }
    }    
}
Super_Hippo Super_Hippo

2015/4/27

#
Like 24 says that you have to click exactly the right cell. If the cell size is 1, then this is unlikely to happen. You could remove lines 24, 25, 28 and change the 'null' in line 22 to 'this'. It would be better to have the checks the other way around though:
public void act() 
{
    if (Greenfoot.mouseClicked(this))
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if(mouse!=null && mouse.getButton() == 1)
        {
            Greenfoot.setWorld(new Hydraboss());
        }
    }
}
I am not sure if the 'getMouseInfo' can return 'null' at all if there was a click on an object in the world, so you may be able to just use this there instead of the two lines:
Greenfoot.getMouseInfo().getButton() == 1)
TheGoldenBucket TheGoldenBucket

2015/4/27

#
Never mind! Just ended up using Greenfoot.mouseClicked() in the end. -TheGoldenBucket
danpost danpost

2015/4/27

#
You could code it this way to act on a specific mouse button:
import greenfoot.*;
 
public class HydraButton extends Actor
{
    public void act() 
    {
        if (Greenfoot.mouseClicked(this) && Greenfoot.getMouseInfo().getButton() == 1)
            Greenfoot.setWorld(new HydraBoss());
    }    
}
You need to login to post a reply.