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

2018/4/2

Enemy Movement

student1 student1

2018/4/2

#
I'm making a game and i want to make it so that the enemy is on a platform and the enemy moves from one side of the platform to the other and back again. i also want it so the the enemy is continuously going back and forth.
Steve9719 Steve9719

2018/4/2

#
Do you have any code written yet? I'm still new to Greenfoot but I'll try to help if I can.
danpost danpost

2018/4/2

#
Your enemy just needs a direction indicator -- a field that gives the current direction of movement and is used (1) when moving the enemy; and (2) to determine when to change direction:
1
2
3
4
5
6
7
8
9
10
11
12
// field
int dir = 1;
 
// movement code
move(dir); // can be multiplied by a speed value
// possible turning about code
setLocation(getX(), getY()+2);
Actor platform = getOneIntersectingObject(Platform.class);
setLocation(getX(), getY()-2);
int pX = platform.getX();
int pW = platform.getImage().getWidth();
if ((dir < 0 && pX-pW/2 >= getX()) || (dir > 0 && pX+pW/2 <= getX())) dir = -dir;
student1 student1

2018/4/2

#
thank you danpost it works perfectly, now i just need to figure out how to make it change images when it gets to one side so that it looks like its turning
Asenoju Asenoju

2018/4/2

#
You could name your Image something like "enemy1" for the enemy facing right, and "enemy-1" for the enemy facing left. Then you could add the following line of code into the if-statement danpost made for you:
1
2
3
4
5
6
if ((dir < 0 && pX-pW/2 >= getX()) || (dir > 0 && pX+pW/2 <= getX()))
{
dir = -dir;
setImage("enemy" + dir + ".png")
//Replace .png with whatever format your image is saved as.
}
That's just the most simple way I can think of. Another thing you could do is simply flip the image (I'm assuming you just want the image to face to the opposite direction). What you could do then is:
1
2
3
4
5
if ((dir < 0 && pX-pW/2 >= getX()) || (dir > 0 && pX+pW/2 <= getX()))
{
dir = -dir;
getImage().mirrorHorizontally();
}
student1 student1

2018/4/2

#
Asenoju, it works perfectly and just what i was looking for thank you
You need to login to post a reply.