随机弹跳球
Random bouncing ball
我在网上找到了一些解释如何让球弹跳的答案,但其中一些对我没有帮助(因为弹跳不是随机的),还有一些非常困难(我的物理知识有限) .
问题:我有一个球会移动和弹跳,但不是随机的,我想让这个球随机弹跳。
我已经有了这段代码:
Public Class Ball{
/** Coordinates */
private int x, y;
/** Speed of the ball*/
private int speedX, speedY;
public Ball(int x, int y, int speedX, int speedY) {
this.x = x ;
this.y = y ;
this.speedX = speedX;
this.speedY = speedY;
}
public void moveAndBounce() {
x += speedX ;
y += speedY ;
// Assuming that touchWallHorizontal() and touchWallHorizontal() work
if (touchHorizontalWall()) {
speedX = -speedX ;
}
if (touchVerticalWall()) {
speedY = -speedY ;
}
}
public static void main (String [] args){
Ball ball = new Ball(); // Initialisation
while (true){
ball.moveAndBounce() ;
}
}
}
效果很好,但球的运动总是一样的(矩形)。
问题:有没有办法在不给球添加属性的情况下进行随机弹跳(只需要坐标和速度)?
如果没有,是否有解决此问题的难点?
提前致谢!
问题已解决。这是 moveAndBounce() 方法的新代码(感谢 johnHopkins):
public void moveAndBounce() {
x += speedX ;
y += speedY ;
Random random = new Random();
if (touchHorizontalWall()) {
if (speedX > 0) {
// New speed between 10 and 15 (you can choose other)
setSpeedX(-random.nextInt(15) + 10);
} else {
setSpeedX(random.nextInt(15) + 10
}
}
if (touchVerticalWall()) {
if (speedY > 0) {
setSpeedY(-random.nextInt(15) + 10);
} else {
setSpeedY(random.nextInt(15) + 10);
}
}
}
我在网上找到了一些解释如何让球弹跳的答案,但其中一些对我没有帮助(因为弹跳不是随机的),还有一些非常困难(我的物理知识有限) .
问题:我有一个球会移动和弹跳,但不是随机的,我想让这个球随机弹跳。
我已经有了这段代码:
Public Class Ball{
/** Coordinates */
private int x, y;
/** Speed of the ball*/
private int speedX, speedY;
public Ball(int x, int y, int speedX, int speedY) {
this.x = x ;
this.y = y ;
this.speedX = speedX;
this.speedY = speedY;
}
public void moveAndBounce() {
x += speedX ;
y += speedY ;
// Assuming that touchWallHorizontal() and touchWallHorizontal() work
if (touchHorizontalWall()) {
speedX = -speedX ;
}
if (touchVerticalWall()) {
speedY = -speedY ;
}
}
public static void main (String [] args){
Ball ball = new Ball(); // Initialisation
while (true){
ball.moveAndBounce() ;
}
}
}
效果很好,但球的运动总是一样的(矩形)。
问题:有没有办法在不给球添加属性的情况下进行随机弹跳(只需要坐标和速度)?
如果没有,是否有解决此问题的难点?
提前致谢!
问题已解决。这是 moveAndBounce() 方法的新代码(感谢 johnHopkins):
public void moveAndBounce() {
x += speedX ;
y += speedY ;
Random random = new Random();
if (touchHorizontalWall()) {
if (speedX > 0) {
// New speed between 10 and 15 (you can choose other)
setSpeedX(-random.nextInt(15) + 10);
} else {
setSpeedX(random.nextInt(15) + 10
}
}
if (touchVerticalWall()) {
if (speedY > 0) {
setSpeedY(-random.nextInt(15) + 10);
} else {
setSpeedY(random.nextInt(15) + 10);
}
}
}