Java游戏计时动作

时间:2012-05-29 07:56:42

标签: java timer move

我正试图让球从窗户顶部掉下来。我将球对象存储在ArrayList中,目前我正在这样做。

for (int i = 0; i < balls.size(); i++) {
    Ball b = (Ball) balls.get(i);
    if (b.isVisible()) {
        b.move();
    }

移动功能只是改变球的y坐标,使其下降到屏幕上。

目前,所有人都在同一时间进行绘画并完全同时出现。

e.g。 http://puu.sh/xsGF

如何制作它们以便随机播放?

我的move()函数如下。

    public void move() {

    if (y > 480) {
        this.setVisible(false);
        System.out.println("GONE");
    }
    y += 1;
}

4 个答案:

答案 0 :(得分:1)

你可以在游戏循环中随机添加球。

//add new balls randomly here:
if(<randomtest>) {
    balls.add(new Ball());
}
for (int i = 0; i < balls.size(); i++) { 
  Ball b = (Ball) balls.get(i); 
  if (b.isVisible()) { 
      b.move(); 
  }
  else {
    //also might be good idea to tidy any invisible balls here
    //if you do this make sure you reverse the for loop
  }
}

答案 1 :(得分:0)

你可以做两件事:

  1. 添加计时器。当定时器熄灭时(例如每10毫秒),选择一个随机球,然后让它下降1px。 (介意,由于随机因素,你会得到在不同时间以不同速度下降的球

  2. 初始化球时使用随机值作为速度。用该速度值增加y坐标,这样球就会以不同的速度下降。

答案 2 :(得分:0)

最简单的方法,如果你想要恒定的速度,就是将它们置于视口顶部的随机位置。

因为我猜你已经把它们画在屏幕之外,只需在那里添加一个随机位移,你就完成了。例如:

ball.y = -radius + random.nextInt(100);

答案 3 :(得分:0)

好的,看到你的移动功能,这在物理上并不正确。你应该加速。这使得球更加逼真(当然还有空气阻力等,但我认为这已经足够了)。为了让它们随机下降,您可以随机添加它们(使它们在随机时间实例中存在/可见)左右。

class Ball {
  private double acc = 9.81; // or some other constant, depending on the framerate
  private double velocity = 0;
  private double startFallTime = Math.random()*100; // set from outside, not here!

  public void move() {
    // check if ball is already here
    if (startFallTime-- > 0) return;
    if (y > 480) {
      this.setVisible(false);
      System.out.println("GONE");
    }
    velocity += acc; 
    y += velocity;
  }
}

编辑:当然加速的东西是可选的,取决于你想要的。如果你想要线性运动,那么你的方法很好,如果球有加速度,它看起来会更好。 ;)另外,我建议在随机实例中添加球,而不是使用我使用的startFallTime,因为这在物理上并不正确。取决于你的需求,所以你必须自己找出正确的方法。

相关问题