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

2019/4/14

Enemy Movement

Hectic Hectic

2019/4/14

#
I want to do a basic space invaders sort of game as I am fairly new to using this software. I was wondering if there is a way to move the Enemy actor, being a small little alien, a set distance in certain directions and then to loop the process over and over again.
AdiBak AdiBak

2019/4/14

#
You could use the setRotation() (or turn) method to determine the directions, and move(int distance) to make the enemy move a certain distance. You can find the api for these methods here You could use a for loop to loop the process over and over again. Here's an example:
public void act(){
   for (int i = 0; i < [number of times]; i++){
      setRotation([amount]);
      move( [ int amount] );
   }
}
This is how the structure would look like. The words in the brackets indicate that you can come up with those values.
Super_Hippo Super_Hippo

2019/4/14

#
You should not use a for-loop for moving like this or it will move all the steps and you will only see the result after everything is finished. You will need the following: - a variable to save the direction it is moving right now (right or left) - when the actor is at the left or right edge of the screen, move it down and change the direction The direction variable can be an int which can be -1 (left moving) or +1 (right moving), so you can multiply it when moving:
setLocation(getX()+direction*speed, getY());
Then, when changing direction, you simply multiply the variable with -1.
You need to login to post a reply.