我正在使用Slick2D库在 Java 中制作塔防游戏。 一个问题是我的子弹数学。现在,子弹将在敌人当前的X,Y坐标后射击 - 但是当敌人在子弹到达X时移动,Y将会落后。除了加速子弹外,还有什么想法解决这个问题吗?子弹数学在子弹类的底部。
public class Bullets implements GameObject {
private ArrayList<Bullet> bulletList = new ArrayList<Bullet>();
Enemy enemy = new Enemy();
BasicTower basicTower = new BasicTower();
public Shape bulletCircle = null;
public boolean collides = false;
public int bulletCount;
public Bullets() throws SlickException {
}
@Override
public Vector2f getPosition() {
return null;
}
@Override
public void init(GameContainer gc, StateBasedGame stateBasedGame) throws SlickException {
}
@Override
public void render(GameContainer gc, StateBasedGame stateBasedGame, Graphics g) throws SlickException {
for (int i = 0; i < bulletList.size(); i++) {
Bullet bullet = bulletList.get(i);
bulletCircle = new Circle(bullet.location.getX(),bullet.location.getY(),10);
if (bulletCircle.intersects( enemy.playerRectangle )){
bulletCount++;
bulletList.remove( i );
collides = true;
}else{
collides = false;
}
g.setColor( red );
g.fill(bulletCircle);
}
}
@Override
public void update(GameContainer gc, StateBasedGame stateBasedGame, int delta) throws SlickException {
//Update the bullet's position.
Input input = gc.getInput();
//enemy.update(gc, stateBasedGame, delta);
for (int i = 0; i < bulletList.size(); i++) {
Bullet bullet = bulletList.get(i);
bullet.move();
}
}
public void addNewBullet2(float x1, float y1, float x2, float y2) {
bulletList.add(new Bullet(x1*64+48,y1*64+48, x2, y2));
}
class Bullet {
float startX = 0;
float startY = 0;
float destX = 0;
float destY = 0;
Point location = new Point(0, 0);
float speed; //how fast this moves.
float dx;
float dy;
public Bullet(float startX, float startY, float destX, float destY) {
this.startX = startX;
this.startY = startY;
location.setLocation(startX, startY);
this.destX = destX;
this.destY = destY;
recalculateVector(destX, destY);
}
public void recalculateVector(float destX, float destY) {
float rad = (float) (Math.atan2(destX - startX, startY - destY));
//Can set different speeds here, if you wanted.
speed = 5;
this.dx = (float) Math.sin(rad) * speed;
this.dy = -(float) Math.cos(rad) * speed;
}
public void move() {
float x = location.getX();
float y = location.getY();
x += dx;
y += dy;
location.setLocation(x, y);
}
}
答案 0 :(得分:1)
这只是一个线性的albegra问题。你的目标是在你开始射击时敌人所在的点P0。但相反,当你的子弹到达时,你需要指出它们是什么时候。 所以你需要敌人的速度,子弹速度和射手距离来获得正确点的坐标。
然而,由于数学可能变得棘手(例如,如果目标不遵循一条线),你可以尝试使子弹跟随目标,这当然会导致曲线轨迹。
答案 1 :(得分:0)
你可能需要考虑每个敌人的速度。因此,如果您拥有更快或更慢的敌人,您可以使用敌人速度调整子弹发送的位置。而不是仅仅将子弹发送给敌人X&amp;是的,你加入敌人X&amp; Y基于他们的速度。这将在敌人面前稍微发射子弹以补偿敌人的速度。