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

2016/4/2

How to do something on second click, when that second click is on the World.

iansprograms iansprograms

2016/4/2

#
Hello, so I won't have any code here, but I'll explain what I'm trying to do. So there is a button, when you click the button you must click the ground (background). When you use your second click on the background, a cube will spawn. And Of course, the amount of clicks you've made resets after the process is finished. Also, how do I call different Actors inside an Actor script? If there needs to be clarification, just ask! Thanks!
Super_Hippo Super_Hippo

2016/4/2

#
In your button class:
private int click = 0;

public void act()
{
    if (click == 1)
    {
        if (Greenfoot.mousePressed(getWorld())
        {
            click = 0;
            MouseInfo mouse = Greenfoot.getMouseInfo();
            getWorld().addObject(new Cube(), mouse.getX(), mouse.getY());
        }
        else if (Greenfoot.mousePressed(null) && !Greenfoot.mousePressed(this))
        {
            click = 0;
        }
    else if (Greenfoot.mousePressed(this)) click = 1;
}
Does this work as you wanted?
danpost danpost

2016/4/2

#
I would use an Actor field instead of an int click field (you may want to have more buttons to add different things into the world). This would be done by the following:
/** in world class */

// instance fields
private Actor cubeBtn;
private Actor toBeSpawned;

// in constructor
cubeBtn = new SimpleActor();
cubeBtn.setImage(new GreenfootImage("cube.png");

// in act
if (Greenfoot.mouseClicked(null) && !Greenfoot.mouseClicked(this)) toBeSpawned = null;
if (Greenfoot.mouseClicked(cubeBtn)) toBeSpawned = new Cube();
if (toBeSpawned != null && Greenfoot.mouseClicked(this))
{
    MouseInfo mouse = Greenfoot.getMouseInfo();
    addObject(toBeSpawned, mouse.getX(), mouse.getY());
    toBeSpawned = null;
}
with a SimpleActor class (the entire class is shown here) of
public class SimpleActor extends greenfoot.Actor {}
This class allows an Actor object to be created without any extra state or behavior added to it. It is actually very versatile if used properly.
You need to login to post a reply.