We’ll start by making the Enemy class, which will let us create as many enemies as we want. You can call this class anything that you’d like.
You will then want to extend Sprite so that the compiler knows that this class will be a Sprite.
public class Enemy extends Sprite
{
}
We’ll want to write the constructor next. This will let us create the initial data and settings for this this. In the constructor we want to make sure that we create the body and fixtures for this Sprite, so that things can collide with it and we can attach graphics to the body. Create a defineBody() method just like we did in Player. You can copy the code from Player’s define body method if you’d like.
You constructor and defineBody() will look something similar to this:
public Enemy() {
defineBody();
}
public void defineBody() {
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(32, 32);
bodyDef.type = BodyDef.BodyType.DynamicBody;
box2Body = world.createBody(bodyDef);
FixtureDef fixtureDef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(8); //you can change these values as you want
fixtureDef.shape = shape;
box2Body.createFixture(fixtureDef).setUserData(this);
}
This will create a body for the Enemy, but we need to be able to access the world where the Enemy will be put into. We will make some variables that will be useful. Create a World variable and a Body variable:
private World world;
private Body box2Body;
We can then pass the world that the enemy will live in through the constructor:
public Enemy(World world) {
this.world = world;
defineBody();
}
You will now be able to make enemies in the Screen that you want. In the constructor, after creating the world, you can now use
Enemy enemyName = new Enemy(world);
You can duplicate this line many time depending on where you want to place your Enemy.
Follow the video below to see how to best set enemies in different positions and how to make sure that you can interact with them.