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

2017/3/25

How do I move my enemies?

11870 11870

2017/3/25

#
I want to have goblins walking back and forth through hallways. They turn around when they encounter a rock. I tried writing a can move for this, but it is not running properly. I'm just completely lost for how to do this. So far I have functions for moveUp() and moveDown() (those work) and a canMove() boolean (that properly could use some revising). Can anyone help?
Super_Hippo Super_Hippo

2017/3/25

#
It would help if you could show what you have tried. (Can't revise code without seeing it.)
11870 11870

2017/3/25

#
Sure. As you can see, I resorted to confining it's space with coordinates on the y axis (still doesn't work). Meanwhile, the canMove() boolean is what remains of my previous attempts (saying something like "while(canMove()){...}. The problem was that I wasn't sure how to put it in run since it was looping itself, and it would just go back down as soon as it started going up.
public void act() 
    {
        // Add your action code here.
        getImage().scale(50,50);
        animationCounter++;
        patrol();
    }    
    
    public boolean canMove()
    {
        if(getObjectsInRange(20, Rock.class).isEmpty())
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
    
    public void patrol()
    {
            if(getY() <= 200 && getY() >= 50)
            {
                moveDown();
            }
            else
            {
                moveUp();
            }
    }
Super_Hippo Super_Hippo

2017/3/25

#
You need to save in which direction it is moving right now and then, change the direction when it hits the edge. You can save it as a boolean or as an int:
private int direction = 1; //1=down, -1=up

public void act()
{
    //do not scale the image in the act method. You can do that in the constructor (it only needs to be done once)
    if (getY()>200 || getY()<50) direction *= -1;
    setLocation(getX(), getY() + direction /** * speed */;
}
11870 11870

2017/3/27

#
Thanks! That worked!
You need to login to post a reply.