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

2019/6/16

Get the class the mouse is clicking on

Fargesia Fargesia

2019/6/16

#
Hi, I was wondering, how do you know which class the mouse is clicking on? Cause the mouseClicked method uses an actor and not a class. Basically I want to do something like: if(Greenfoot.mouseClicked(className.class){...} I know this won't work but how can I get a class instead of an actor? Thanks!
Nosson1459 Nosson1459

2019/6/16

#
is it that you want all the objects of one class to do something when only one of them is clicked?
Fargesia Fargesia

2019/6/16

#
No, the objects of this class won't do anything. It would be like if you click on a cookie.class object, a human eats it (that's just an exemple). I just want to use the if( you click on any object of this class) condition.
Super_Hippo Super_Hippo

2019/6/16

#
You say "if any object of a class is clicked" but you also say "eat the cookie". Both are different things. If you want to eat the cookie which is clicked, then you don't need to check if any cookie is clicked. You need to know which cookie is clicked if any is clicked. So knowing if any is clicked is not giving you any advantage. Look at this:
boolean clickedOnCookie = false;
for (Actor cookie : getWorld().getObjects(Cookie.class))
{
    if (Greenfoot.mouseClicked(cookie))
    {
        clickedOnCookie = true;
    }
}

if (clickedOnCookie)
{
    //do whatever you want to do if any cookie is clicked
}
This can be seen as a "click on any object of the class" condition, but it probably isn't what you need. The simplest thing would be if each Cookie checks for clicks on itself:
public void act()
{
    if (Greenfoot.mouseClicked(this))
    {
        //tell human to eat it
    }
}
Otherwise, the first code can be simplified as this:
for (Actor cookie : getWorld().getObjects(Cookie.class))
{
    if (Greenfoot.mouseClicked(cookie))
    {
        //eat cookie here
        break; //can't click on two cookies at the same time, so we can stop when one was found
    }
}
You need to login to post a reply.