Я сейчас играю в javaFX. По сути, игрок знает, какой тип пули у него есть (скажем, SingleShot). Все типы пуль расширяются от общего класса снарядов. В классе игрока у меня есть метод, который должен порождать пулю, если нажата кнопка. Как я могу породить клона пули, учитывая только его тип? Так что, если мой тип - SingleShot (хранится в виде поля Projectile), как мне создать новый SingleShot без набора операторов if-else, проверяющих каждый тип?
public class Projectile extends Sprite{
int damage;
int fireRate;
public Projectile(Pane outerPane, double x, double y, double dy, double dx){
super(outerPane,x,y,dy,dx);
damage = 1;
fireRate = 10;
}
public int getFireRate(){
return this.fireRate;
}
public void setFireRate(int fr){
fireRate=fr;
}
public int getDamage(){
return damage;
}
public void setDamage(int d){
damage=d;
}
}
Это пример пули, но есть много других. В данном классе пули также может быть несколько фигур / прямоугольников.
public class SingleShot extends Projectile{
Rectangle bullet;
public SingleShot(Pane outerPane, double x, double y,double dy, double dx){
super(outerPane,x,y, dy, dx);
bullet = new Rectangle(0,0,10,10);
bullet.setFill(Color.BLUE);
getChildren().add(bullet);
}
}
Вот класс игрока. Я удалил большую часть постороннего кода, но, если вам это нужно, пожалуйста, спросите.
public class Player extends Sprite{
Rectangle plyr;
AnimationTimer timer;
boolean movingN,movingE,movingW,movingS;
boolean shootingN,shootingE,shootingW,shootingS;
Projectile bulletType;
ArrayList<Projectile> bullets;
public Player(Pane outerPane, double x, double y, double w, double h, double xv, double yv){
bulletType = new SingleShot(this,0,0,1,1);
bullets= new ArrayList<Projectile>();
}
private void shoot(){
if(shootingN){
System.out.println("North shot");
//how to determine what shot to create? possibly have hard checker for type
//maybe have a method which makes a copy for the projectile type, then feeds it to here and this only changes vx,vy,x,y, etc.
Projectile shot = new SingleShot(this,plyr.getX()+0.5*plyr.getWidth(),plyr.getY(),0,-10);
getChildren().add(shot);
bullets.add(shot);
}
}