[英]Java game timing movements
我试图使球从窗户的顶部掉落。 我将球对象存储在ArrayList中,此刻,我正在这样做。
for (int i = 0; i < balls.size(); i++) {
Ball b = (Ball) balls.get(i);
if (b.isVisible()) {
b.move();
}
移动功能仅更改球的y坐标,因此它会向下移动到屏幕上。
此刻,它们都在完全相同的时间绘制并且在完全相同的时间掉落。
我该如何使它们以随机间隔掉落?
我的move()函数如下。
public void move() {
if (y > 480) {
this.setVisible(false);
System.out.println("GONE");
}
y += 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
}
}
您可以执行以下两项操作:
添加一个计时器。 当计时器关闭时(例如,每10毫秒关闭一次),请选择一个随机的球,然后让其下降1像素。 (请注意,由于随机因素,您会得到在不同时间以不同速度掉落的球 )
初始化球时,请使用随机值作为速度。 将y坐标增加该速度值,这样,球将全部通过球网以不同的速率掉落。
如果要保持恒定的速度,最简单的方法是将它们放置在视口顶部的随机位置。
由于我猜您已经将它们绘制在屏幕外部,因此只需在其中添加随机位移即可。 例如:
ball.y = -radius + random.nextInt(100);
好吧,看到您的移动功能,这在物理上并不正确。 你应该加速。 这使球落得更逼真(当然还有空气阻力等,但我认为现在就足够了)。 为了让它们在随机时间掉落,可以在随机时间添加它们(使它们在随机时间实例存在/可见)。
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一起使用,因为这在物理上是不正确的。 不过,这取决于您的需求,因此您必须自己找出正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.