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

2017/1/23

How can i get enemys to move but not go past a ceratin y co - ordinate

jrod159 jrod159

2017/1/23

#
so i am creating a game where the ship you control is at the bottom and and enemies randomly appear and move and the enemies shoot at the player ship and the player ship has to shoot them but i don't know how to get to randomly move but not go past a certain point becuase i dont want them running into the ship at the bottom any help with this would be much appreciated
Nosson1459 Nosson1459

2017/1/24

#
Just put your moving in an 'if' statement. So for instance if you have 'move(3)' , just put that in an if, like:
if (getY() <= 575) // this will make sure that the enemy won't go past 575 on the y axis
{
    move(3); // code for moving
}
this code should probably go on the innermost part of your moving ifs in your enemy class, but I can't say for sure since I haven't seen your code.
Super_Hippo Super_Hippo

2017/1/24

#
Well, this doesn't prevent the enemies from going into the restricted area. The enemy can still move to 576 and then it will stop. If you import the Animal class, there is a 'atWorldEdge' method looking like this:
    public boolean atWorldEdge()
    {
        if(getX() < 20 || getX() > getWorld().getWidth() - 20)
            return true;
        if(getY() < 20 || getY() > getWorld().getHeight() - 20)
            return true;
        else
            return false;
    }
Usually used like "if the object is at the edge of the world, turn it around". If you change the last part to about 'getY() > 555', you could use it for your problem.
jrod159 jrod159

2017/1/24

#
ok thanks for the help guys :)
You need to login to post a reply.