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

2017/12/7

How to make enemies go from one side to the other

Toaster Toaster

2017/12/7

#
I'm working on a project for my school, and I am almost done but I need my enemies to move from one side to the other. Any help is appreciated. Thanks!
  /**
     * One of the enemies for Hunter, but doesn't shoot at Hunter because Enemy4 shoots a lot 
     * quicker and more bullets than Hunter. 
     */
    public void act() 
    {
        Actor bullet = getOneIntersectingObject(Bullet.class);
        move();
        if (bullet !=null)
        {
          getWorld().removeObject(this);  
        } 
     }
public void shoot()
{
    getWorld().addObject(new Bullet2(), getX(), getY());
}
public void move()
{
    if (isAtEdge())
    { 
     setLocation(getX()-STEP_SIZE,getY());   
    } else {
    setLocation(getX()+STEP_SIZE,getY());
}
}
Super_Hippo Super_Hippo

2017/12/7

#
You need to add 'move(1);' or something somewhere.
danpost danpost

2017/12/7

#
You need to keep track of which direction the enemy is going and change direction when the direction and end edge are in phase with each other. That is, more simply, if moving right and found at right edge or if moving left and found at left edge, change directions.
Super_Hippo Super_Hippo

2017/12/7

#
Right, I wasn't looking closely there. Ignore my post.
Toaster Toaster

2017/12/8

#
So what method would I use?
danpost danpost

2017/12/8

#
Toaster wrote...
So what method would I use?
After adding the field, you will change the 'move' method code. In it, you will first move, then check and change direction if needed.
Toaster Toaster

2017/12/8

#
I don't understand, do I need something like a check method?
Super_Hippo Super_Hippo

2017/12/8

#
private int direction = 1;

public void act()
{
    setLocation(getX()+STEP_SIZE*direction, getY()); 
    if (isAtEdge()) direction *= -1;
}
You need to login to post a reply.