几天前,我开始开发一款'简单'的2D游戏。我试图用"实体系统"来做到这一点。我得到了"游戏对象"类,它扩展了所有其他对象,如树木、敌人(史莱姆)等。所有这些游戏对象都存储在名为"游戏对象"的 arrayList 中。然后我使用 for 循环来迭代列表中的所有对象并调用它们的基本函数,如 update() 和 draw()。到目前为止,一切正常,即使我不是 100% 确定为什么。问题是,由于某种原因,我不能对碰撞做同样的事情。
我知道这个话题在这里讨论了很多次,但即使过了很多天我也无法解决这个问题。有人可以帮我吗?另外,我为我的英语道歉。
游戏类:
public class Game extends BasicGame
{
public Game()
{
super("Game");
}
public void init(GameContainer gameContainer) throws SlickException
{
World.init();
}
public void update(GameContainer gameContainer, int delta) throws SlickException
{
World.update();
}
public void render(GameContainer gameContainer, Graphics g) throws SlickException
{
World.draw(g);
}
}
游戏对象类:
public abstract class GameObject
{
protected void update()
{
}
protected void draw()
{
}
}
树类:
public class Tree extends GameObject
{
public float x, y;
private static Image tree;
public Tree(float x, float y)
{
this.x = x;
this.y = y;
tree = Resources.miscSheet.getSprite(2, 0);
}
public void draw()
{
tree.draw(x, y)
}
}
史莱姆类:
public class Slime extends GameObject
{
public static float x;
public static float y;
private static Animation slimeAnim;
public Slime(int x, int y)
{
this.x = x;
this.y = y;
// My own method for loading animation.
slimeAnim = Sprite.getAnimation(Resources.slimeSheet, 0, 0, 5, 300);
}
public void update()
{
// *Random movement here*
}
public void draw()
{
slimeAnim.draw(x, y);
}
}
世界级:
public class World
{
public static List<GameObject> gameObjects = new ArrayList<GameObject>();
public static void init()
{
Tree tree = new Tree(0, 0);
Tree tree2 = new Tree(200, 200);
Slime slime = new Slime(80, 80);
gameObjects.add(tree);
gameObjects.add(tree2);
gameObjects.add(slime);
}
public static void update()
{
for (int i = 0; i < gameObjects.size(); i++)
{
GameObject o = gameObjects.get(i);
o.update();
}
}
public static void draw(Graphics g)
{
g.setBackground(new Color(91, 219, 87));
for (int i = 0; i < gameObjects.size(); i++)
{
GameObject o = gameObjects.get(i);
o.draw();
}
}
}
主类:
public class Main
{
public static AppGameContainer container;
public static void main(String[] args) throws SlickException
{
container = new AppGameContainer(new Game());
container.setDisplayMode(1024, 600, false);
container.setShowFPS(false);
container.start();
}
}
我删除了之前的所有碰撞尝试,并跳过了一些其他不必要的内容。我现在如何实现碰撞,例如树木和史莱姆之间的碰撞?
我通常做的是从我的顶级对象类上的矩形继承。如果您的游戏对象类继承自矩形,则在每个实例中都将intersects
方法,这为您提供了一种轻松检测冲突的方法。
class GameObject extends Rectangle{}
问题将是在所有对象之间进行测试。这将是相当沉重的,但仍然是可能的。
for (int i = 0; i < gameObjects.size(); i++) {
for (int j = i; j < gameObjects.size(); j++) {
if (gameObjects.get(i-1).intersects(gameObjects.get(j)) {
// I don't know what you want to do here
}
}
}
这样,您只需将对象 A 与对象 B 进行比较一次。