我在写坦克游戏。我想有一种叫做射击的方法,当我按下Space时,坦克必须射击。我的问题是,当程序调用此方法时,它将经历while循环,然后打印出球的结束位置。我需要在while循环中实现一些功能,每次它计算dx和dy时,它都要使用paint方法并绘制球的新位置。我尝试添加paintImmediately(),但会引发stackoverflow错误。谢谢你帮我
实际上,我正在更改dx和dy,并且我想使用paint方法在该位置绘制球...
public void shoot(Image img, double fromx, double fromy, double ydestination, int speed) {
int time = 0;
double speedy, speedx;
while (dy!=ydestination) {
time++;
speedy = speed * Math.sin(Math.toRadians(angle));
speedx = speed * Math.cos(Math.toRadians(angle));
dy = (int) ((-5) * time * time + speedy * time + fromy);
dx = (int) (speedx * time + fromx);
// paintImmediately((int)dx,(int) dy, 10, 10);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
这是我覆盖的绘画方法,最后一行是我的问题的项目符号:
@Override
public void paint(Graphics g) {
System.out.println("paint");
super.paint(g);
render(bufferedGraphics);
g.drawImage(bufferedScreen, 0, 0, null);
// System.out.println(x1);
BufferedImage buff = rotateImage(mile1, angle);
BufferedImage buf = rotateImage(mile2, angle);
g.drawImage(buff, mx1 - 40, my1, null);
g.drawImage(buf, mx2 , my2, null);
g.drawImage(bullet, (int) dx, (int) dy, null);
//setVisible(true);
}
如果您的绘图代码sleep()
中引入了等待,那么您所做的事情确实的确很错误。您想在那里睡觉是因为您希望屏幕不断更新新的位置...但是您实际上是在使屏幕完全冻结,因为Java Swing中只有1个线程在绘制图形。如果您使该线程处于休眠状态,则不会绘制任何内容(您甚至无法按任何键或使用鼠标)。
相反,您应该做的是通过几次对paint()方法的调用来更新子弹的位置。用伪代码:
paint(Graphics g) {
// calls paint() on all objects in the game world
}
// you should call this once per frame
update(World w) {
// call update() on each game-world object
}
// in Tank
fire(Tank t, Point target) {
// creates a bullet at the tanks' position, and adds it to the World
}
// within Bullet
update() {
// moves this bullet along its path to its target;
// if target reached, add an explosion there and destroy the bullet
}
// within Explosion
update() {
// advance to next explosion frame;
// or if finished, destroy the explosion object
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句