【发布时间】:2012-01-18 22:41:29
【问题描述】:
我目前正在使用组件模式制作一款游戏,并且一直想知道这是如何做到的。 我有一个实体,它实际上只是一袋组件。每个组件都扩展了 Component 类,该类仅具有一些基本功能。
扩展组件类,创建新组件,用于处理输入、图形等。现在问题来了;当我试图从实体中获取特定组件时,它总是返回基本的 Component 类,这会阻止我使用特定的组件函数。
public class GameEntity
{
private ArrayList<Component> components;
public GameEntity()
{
components = new ArrayList<Component>();
}
public void addComponent(Component component)
{
components.add(component);
}
public void update()
{
}
public Component getComponent(Class type)
{
for (Component component : components)
{
if(component.getClass() == type)
{
//return component as Class;
}
}
return null;
}
public void draw(Canvas canvas)
{
for (Component component : components)
{
component.update();
component.draw(canvas);
}
}
}
一些示例组件:
公共类 GraphicsComponent 扩展组件 {
公共位图位图; 公共矩形 currentFrameRect; 私有 ArrayList spriteAnimations; 公共 SpriteAnimation 当前动画;公共 int x = 0;公共 int y = 50;民众 图形组件(){ spriteAnimations = new ArrayList(); }
/** * Adds image [converts to spriteanimation] * @param image */ public void addImage(Bitmap image, String label) { Rect[] tmpRects = {new Rect(0, 0, image.getWidth(), image.getHeight())} ; addAnimation(new SpriteAnimation( image, tmpRects, label )); } public void addAnimation(SpriteAnimation spriteAnimation) { spriteAnimations.add(spriteAnimation); if(currentAnimation == null) { currentAnimation = spriteAnimation; } } @Override public void update() { currentFrameRect = currentAnimation.frames[currentAnimation.currentFrame]; }@Override public void draw(Canvas canvas) {
if(currentAnimation != null) { currentAnimation.draw(x, y, canvas); } }
public int getWidth()
{
return currentAnimation.frames[currentAnimation.currentFrame].width();
}
public int getHeight()
{
return currentAnimation.frames[currentAnimation.currentFrame].height();
}
}
public class InteractiveComponent extends Component
{
public GraphicsComponent graphics;
public InteractiveComponent(GraphicsComponent graphics)
{
this.graphics = graphics;
}
public boolean isOver(int tapX, int tapY)
{
//left top right bottom
if(tapX > graphics.x && tapX < graphics.x + graphics.getWidth() &&
tapY > graphics.y && tapY < graphics.y + graphics.getHeight()
)
{
return true;
}
return false;
}
}
代码格式似乎有些问题,但应该很清楚。 我无法访问任何特定函数,例如graphicComponent 中的getHeight() 或interactiveComponent 中的isOver(),因为我只返回了一个基本组件。
我想根据传递给 getComponent() 的类返回一个 GraphicsComponent 或 InteractiveComponent。
【问题讨论】:
-
向下转换到你想要的类。
-
示例代码太多了。
-
我不熟悉向下转换这个词,谢谢你提到它。我为冗长的代码道歉,我担心我的问题不够清楚。
标签: java class components