Wednesday, June 2, 2010

Creating a game on Google Android game with Flixel – Enemies.

For this tutorial we will create a few platforms for the enemies to move along. To do this we simply create more FlxBlock objects in the GameState constructor, just like we did with the ground. We will also create a new Enemy object with each of these platforms. Notice that the new Enemy objects are added to their own collection called enemies. This is so we can test for collisions between the enemies and the player as a group.

GameState.java

public GameState()

{

levelBlocks.add(this.add(new FlxBlock(0, 640-16, 640, 16)

.loadGraphic(R.drawable.tech_tiles)));

levelBlocks.add(this.add(new FlxBlock(0, 0, 640, 16)

.loadGraphic(R.drawable.tech_tiles)));

levelBlocks.add(this.add(new FlxBlock(0, 16, 16, 640-32)

.loadGraphic(R.drawable.tech_tiles)));

levelBlocks.add(this.add(new FlxBlock(640-16, 16, 16, 640-32)

.loadGraphic(R.drawable.tech_tiles)));

for (int i = 0; i < player =" new" x =" PLAYER_RUN_SPEED" y =" GRAVITY_ACCELERATION;" x =" PLAYER_RUN_SPEED;" y =" JUMP_ACCELERATION;" gibs =" FlxG.state.add(">> operator is a bit shift, which has the effect of halving a integers value, so width>>1 returns half of width.

public void kill()

{

super.kill();

this.gibs.x = this.x + (this.width>>1);

this.gibs.y = this.y + (this.height>>1);

this.gibs.restart();

}

The Enemy class represents the enemies on the screen. Most of the code in the Enemy class is similar to the Player class: it extends the FlxSprite, sets up the physics of the object and defines and plays some animations.

Enemy.java

package org.myname.flixeldemo;

import java.util.ArrayList;

import java.util.Arrays;

import org.flixel.FlxSprite;

public class Enemy extends FlxSprite

{

protected static final float VELOCITY = 150;

protected int maxXMovement = 0;

protected int startX = 0;

public Enemy(int x, int y, int maxXMovement)

{

super(x, y, R.drawable.enemy, true);

this.y -= this.height;

this.maxXMovement = maxXMovement – this.width;

this.startX = x;

this.velocity.x = VELOCITY;

addAnimation(“idle”, new ArrayList(Arrays.asList(new Integer[] {0, 1})), 12);

play(“idle”);

}

The update function is used to move the enemies horizontally on the screen, reversing direction when they reach the end of the underlying platform.

public void update()

{

super.update();

if (this.x – startX >= maxXMovement ||

this.x <= startX)

{

this.velocity.x = -this.velocity.x;

}

}

}

No comments:

Post a Comment