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

2016/3/27

get instance of class from world

Mewtoo Mewtoo

2016/3/27

#
Hi, i making a simple turn game, and i am stuck in battle system I need to get a enemy i clicked on, but in world and work with him i think i can use mouseInfo.getActor() but it doesnt work how i need my actual code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void act(){
        if(Greenfoot.mouseClicked(player)&&step==0){
            showText("vyber nepřítele", 270, 10);
            step=1;       
        }
        //mouse = Greenfoot.getMouseInfo();
        if(Greenfoot.mouseClicked(Enemy.class)&&step==1){
            target=(Enemy)Greenfoot.getMouseInfo().getActor();
            step=2;
            showText("step:"+target.toString(), 200, 10);
        }
 
        showText("step:"+step, 50, 10);
    }
Any ideas? i am stucked. i need to get enemy i clicked on and save it to target.
danpost danpost

2016/3/27

#
To start with, the 'mouseClicked' method requires an object for the parameter (or 'null' to signify any click to return a true value). However, its implementation is specifically for World or Actor objects (objects that are visible -- a Class is not something that a click can be programmatically checked on. This is what you should do: after determining if a click (any click) is detected, called the 'getActor' method on the MouseInfo object and save the returned Actor object in a variable; then, before checking what type Actor it may be, you need to make sure that the returned value is not 'null' (no Actor object was clicked on); after that, you can use the 'instanceof' keyword to check what type Actor object it may be:
1
2
3
4
5
6
7
8
9
10
11
12
13
if (Greenfoot.mouseClicked(null))
{
    Actor actor = Greenfoot.getMouseInfo().getActor();
    if (actor instanceof Enemy && step == 1)
    {
        target = (Enemy)actor;
       // etc;
    }
    if (actor instanceof Player && step == 0)
    {
        // etc;
    }
}
Although this system of code might work, I do not see why you cannot check for clicks with the Enemy and Player classes themselves and then call methods in the world class when detected. For example, in the Enemy class, you could have in the act method:
1
if (Greenfoot.mouseClicked(this)) ((WorldClassName)getWorld()).enemyClicked(this);
then, in the world:
1
2
3
4
5
6
7
8
public void enemyClicked(Enemy enemy)
{
    if (step == 1)
    {
        target = enemy;
        // etc.
    }
}
Mewtoo Mewtoo

2016/3/28

#
Thanks a lot, it works perfectly :)
You need to login to post a reply.