我试图理解这些代码:
/*
* File: BouncingBallWalls.java
* ---------------------
* This is exercise 15 in chapter 4 of "The Art and Science of Java."
* It requires me to write a program that makes an animated bouncing
* ball on the screen, bouncing off the window edges.
*/
import java.awt.*;
import acm.program.*;
import acm.graphics.*;
public class BouncingBallWalls extends GraphicsProgram {
public void run() {
GOval ball = new GOval (getWidth()/2 - BALL_SIZE/2, getHeight()/2 - BALL_SIZE, BALL_SIZE, BALL_SIZE); /* Centers the ball */
ball.setFilled(true);
ball.setFillColor(Color.BLUE);
ball.setColor(Color.BLUE);
add(ball);
double dx = (getWidth()/N_STEPS);
double dy = (getWidth()/N_STEPS);
while(true) {
ball.move(dx, dy); /* Movement for the ball */
pause(PAUSE_TIME);
if (ball.getY() > getHeight() - BALL_SIZE) { /* Each "if" statement reverses the direction of the ball on one */
dy = dy * -1; /* axis if it hits a boundry */
}
if(ball.getX() > getWidth()- BALL_SIZE) {
dx = dx * -1;
}
if(ball.getY() < 0) {
dy = dy * -1;
}
if(ball.getX() < 0) {
dx = dx * -1;
}
}
}
private static final double N_STEPS = 1000;
private static final double PAUSE_TIME = 2;
private static final double BALL_SIZE = 50.0;
}
我了解以下内容,为什么将gameWidth除以N_STEPS? N_STEPS是什么?
double dx = (getWidth()/N_STEPS);
double dy = (getWidth()/N_STEPS);
private static final double N_STEPS = 1000;
参考:http://tenasclu.blogspot.co.uk/2012/12/first-few-days-of-learning-to-program.html
最佳答案
将屏幕尺寸除以N_STEPS即可得到dx和dy,它们表示您希望球在每个循环中移动的距离。 N_STEPS根据可用的屏幕宽度来定义移动,以便无论屏幕大小如何,相对移动/速度都是相同的。
查看N_STEPS的另一种方法是,它控制球的平滑度和速度。这样做的方式可以使平滑度和速度保持一致,而与屏幕大小无关。较高的N_STEPS将导致每个循环的球运动更平滑/更慢。
请注意您的代码:
double dx = (getWidth()/N_STEPS);
double dy = (getWidth()/N_STEPS);
应该可能是:
double dx = (getWidth()/N_STEPS);
double dy = (getHeight()/N_STEPS);
关于java - Java弹跳球墙,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21456257/