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

2014/1/6

How to use mouseClicked() with the World

1
2
JasonZhu JasonZhu

2014/1/6

#
The parameter of the mouseClicked() method requres an actor, how would I use the World as an actor?
bourne bourne

2014/1/6

#
mouseClicked(java.lang.Object obj) True if the mouse has been clicked (pressed and released) on the given object.
No, it requires an Object. So it accepts Worlds as well
JasonZhu JasonZhu

2014/1/6

#
Oh, I was trying to cast Actor to getWorld(). Thanks for the info!
JasonZhu JasonZhu

2014/1/6

#
    public void add()
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if(mouse==null)return;
        int x = mouse.getX();
        int y = mouse.getY();        
        if(Greenfoot.mouseClicked(getWorld())){
            getWorld().addObject(new Point(),x,y);
        }
    } 
This doesn't seem to work... Does anyone happen to know why?
bourne bourne

2014/1/6

#
Where does add() get called from? And note at line 8, getWorld() could possibly return null. Also note mouseClicked can accept null - which case will return true if the mouse clicked anywhere in the scenario.
JasonZhu JasonZhu

2014/1/6

#
add() gets called from my act method in my MagneticField class. The "new Point()" should actually read "new MagneticField()". And actually, I wouldn't mind it accepting null, as long as it adds a MagneticField() when I click anywhere.
bourne bourne

2014/1/6

#
Okay, so what doesn't seem to work? Sounds like there are no Exceptions thrown?
JasonZhu JasonZhu

2014/1/6

#
No exceptions, just that nothing is added when I click.
bourne bourne

2014/1/6

#
Try replacing Greenfoot.mouseClicked(getWorld()) with Greenfoot.mouseClicked(null) With requiring that the clicked event happens on the World, means if there is any Actor at the location you clicked, nothing happens
JasonZhu JasonZhu

2014/1/6

#
I just happened to try that, still no luck...
bourne bourne

2014/1/6

#
Does add() get called every act cycle?
JasonZhu JasonZhu

2014/1/6

#
I manually added a MagneticField() then I started clicking and only then did it start adding new MagneticFields(). And yes, it does.
bourne bourne

2014/1/6

#
Is add() in the MagneticField class?
danpost danpost

2014/1/6

#
If you do not have a MagneticField object in the world, then the act method is never executed and therefore your mouse clicks will be ignored.
JasonZhu JasonZhu

2014/1/6

#
Wow! *face palm* I know what the problem is now. Thank you bourne and danpost for your help.
There are more replies on the next page.
1
2