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

2013/5/26

A charging ennemy

Solringolt Solringolt

2013/5/26

#
I want to make an enemy that charge my hero as soon as it is in the same y position. I tried a method with the getOneObjectAtOffset() method but without success. How can I solve my problem?
danpost danpost

2013/5/26

#
Hero hero = null;
if (!getWorld().getObjects(Hero.class).isEmpty())
{
    Hero hero = (Hero) getWorld().getObjects(Hero.class).get(0);
}
if (hero != null && hero.getY() == getY())
{
    // code to charge hero
}
or
GreenfootImage image = getImage();
setImage(new GreenfootImage(1200, 1);
Actor hero = getOneIntersectingObject(Hero.class);
setImage(image);
if (hero != null && hero.getY() == getY())
{
    // code to charge hero
}
Solringolt Solringolt

2013/5/26

#
Thx I just deleted the Hero on line 4 to make it work. Can you quickly explain me how this code works? (the first one) And if I want to charge when it's +-20 on y, how do I do that? Is there a "between" operator?
danpost danpost

2013/5/26

#
The first 'if' block says "if the list of Hero objects in the world is not empty, then set 'hero' to the first element from that list.". The second 'if' says "if the hero was found to be in the world and if the y values are equal, then charge." To add the condition that the distance between the two actors is 20 or less (in either direction), just add the extra qualifier(s) to the second 'if' statement:
if (hero != null && hero.getY() == getY() && Math.abs(hero.getX()-getX()) <= 20)
Solringolt Solringolt

2013/5/27

#
I wanted to change the distance for y but your code helped me to do it ;) Thx for everything, I get it working.
You need to login to post a reply.