使用文本文件是可以的,但使用 PNG 或位图图形更好。一个像素可能存储多达 4 个字节的信息,并且可以使用照片处理工具轻松创建。
首先,首先,您应该有一个“实体”或“游戏对象”类,场景中的所有内容都可以继承。示例:
public class Entity
{
public float x, y, width, height;
public void onStep() {}
public void onDraw() {}
public RectF getRectF()
{
RectF rect = new RectF();
rect.left = x;
rect.top = y;
rect.right = x + width;
rect.bottom = y + height;
return rect;
}
}
其次,您应该有一些扩展实体类的不同类,例如 Player 类、Wall 类,可能还有 Coin 类:
public class Player extends Entity {...}
public class Wall extends Entity {...}
public class Coin extends Entity {...}
您的下一步将是覆盖玩家的 step 事件,并且 在该 step 事件中,像这样遍历所有墙壁实体:
@Override public void onStep()
{
for (Entity e : my_active_entities)
{
if (e instanceof Wall)
{
Wall wall = (Wall) e;
if (RectF.intersects(wall.getRectF(), this.getRectF()))
{
// We now know that our player is intersecting with "e"
// We also know that "e" is a wall
wall.doSomething();
this.doSomething();
}
}
}
}
最后,将是创建您自己的舞台加载器。这将遍历您的图形并根据当前像素的颜色在屏幕上绘制对象。
Bitmap bitmap = getOurBitmapFromSomewhere();
for (int x = 0; x < bitmap.getWidth(); x++)
for (int y = 0; y < bitmap.getHeight(); y++)
{
int color = bitmap.getPixel(x, y);
switch (color)
{
case 0xFF00FF00:
// First byte is Alpha
// Second byte is Red
// Third byte is Green
// Fourth byte is Blue
Player player = new Player();
player.x = x * TILE_SIZE; // For example, 16 or 32
player.y = y * TILE_SIZE;
my_active_entities.add(player);
break;
}
}
这总结了我在游戏对象处理、碰撞检测和关卡加载方面的两分钱。任何被此绊倒的人都非常欢迎在他们的软件中使用此代码或此代码概念。