为什么不会倍增? (JAVA)

时间:2015-09-04 23:04:22

标签: java double pong

我正在努力创造Pong,并且正在制作球的物理学。

我有以下代码:

public Ball(Pong pong) {
        random = new Random();
        this.x = pong.width / 2 - this.width / 2;
        this.y = pong.height / 2 - this.height / 2;

        this.pong = pong;

        this.motionX = 2.0;

        this.motionY = random.nextDouble();
        while (this.motionY > 0.7) {
            this.motionY = random.nextDouble();
            System.out.println(motionY);
        }



        multiplier = 8 / this.motionX;
        System.out.println(motionX);
        this.motionX = multiplier * motionX;
        System.out.println(motionX);
        this.motionY *= multiplier;


}

public void update(Paddle paddle1, Paddle paddle2) {
    this.x += this.motionX;
    this.y += this.motionY;

}

public void render(Graphics2D g) {

    Graphics2D gg = (Graphics2D) g;

    g.setColor(Color.WHITE);
    Ellipse2D.Double shape = new Ellipse2D.Double(x, y, width, height);
    g.fill(shape);
}

在Ball方法中,我将motionX设置为2.0。在后来的方法中,我通过乘数运动MotionX,所以我可以使所有球速相同。然而,它应该是2.0 * 8.0(16.0)它与8.0一起出现。每个号码都会发生这种情况。

任何想法有什么不对?

3 个答案:

答案 0 :(得分:3)

你的乘数不是8 ...它是8除以motionX所以当然如果再乘以motionX,它将取消分母。这是你在做什么:

x = 2
m = 8 / x
x = m * x = 8 / x * x = 8

答案 1 :(得分:1)

但是

this.motionX = 2.0;

然后

multiplier = 8 / this.motionX;

然后

this.motionX = multiplier * motionX;

看起来像MotionX对我来说是8。

答案 2 :(得分:0)

解决我的(愚蠢)错误:

我正在划分一个数字然后再乘以它。

解决我的物理问题(让球在桌子上左右移动):

将Ball方法更改为:

public Ball(Pong pong) {
        random = new Random();
        this.x = pong.width / 2 - this.width / 2;
        this.y = pong.height / 2 - this.height / 2;

        this.pong = pong;

        this.motionX = random.nextInt(3) -1;
        while (motionX == 0) {
            this.motionX = random.nextInt(3) -1;
        }

        System.out.println(motionX);


 this.motionY = random.nextDouble();
    while (this.motionY > 0.7) {
        this.motionY = random.nextDouble();
        System.out.println(motionY);
    }

    multiplier = 8.0 / this.motionX;
    if (this.motionX < 0) {
        this.motionX = -(multiplier * motionX);
    }
    else {
        this.motionX = multiplier * motionX;
    }

    this.motionY *= multiplier;


}

我首先确保motionX不能为0(否则球不会向左或向右移动)。

然后我补充说,如果原始motionX是负数,它乘以乘数,然后变为负数。

感谢您的帮助:)