1 回答

TA貢獻1862條經驗 獲得超7個贊
我確實建議盡可能避免繼承。它只會讓您的生活更輕松。相反,請執行以下操作:
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 */
}
這遵循組合優于繼承原則,它允許您保持代碼簡單并提供更多控制權:
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 項目符號)。這將您的邏輯模型與實際物理或渲染代碼分開。確保向武器構造函數添加更多參數,以描述是什么使您的武器與其他武器不同或獨特。然后可以在shoot()方法中使用此信息,使用提供的屬性發射子彈。
添加回答
舉報