我确实建议尽可能避免继承。它只是让你的生活更轻松。相反,可以这样做:
public class Weapon {
private final Bullet template;
public Weapon(Bullet template) {
this.template = template;
}
/* shoot logic here */
}
public class Bullet {
private final Vector2 position;
private final float velocity;
public Bullet(float speed) {
this.position = new Vector2();
this.speed = speed;
}
/* setters and getters */
}
以下是
Composition over Inheritance
原则,允许您保持代码简单,并提供更多控制:
Bullet rifleBullet = new Bullet(2f);
Weapon rifle = new Weapon(rifleBullet);
Bullet shotgunBullet = new Bullet(5f);
Weapon shotgun = new Weapon(shotgunBullet);
/* somewhere in update() */
shotgun.shoot();
rifle.shoot();
这个
shoot()
然后,方法可以实现实际项目符号的创建(例如,使用
libgdx bullets
)这将您的逻辑模型与实际物理或呈现代码分开。确保向武器构造者添加更多的参数来描述是什么使你的武器与其他武器不同或独特。然后可以在
射击()
方法使用提供的属性激发项目符号。