简体   繁体   English

使用随机生成的数字进行动画制作

[英]Using randomly generated numbers for animation

I'm trying to recreate pong and I've run into a bug I can't figure out. 我正在尝试重新创建pong,但遇到了一个我不知道的错误。

So far I've gotten the paddles & ball to display and move how I want for the most part, but I can't seem to make the ball initialize moving in a random direction. 到目前为止,我已经获得了大部分的桨和球来显示和移动我想要的方式,但是我似乎无法使球初始化为沿随机方向移动。

Here is the code that sets the ball's direction 这是设置球方向的代码

        if(inGame == true)
    {
        double start = -1;
        double end = 1;

        Random xRand = new Random();
        double xResult = start + (end - start) * xRand.nextDouble();

        Random yRand = new Random();
        double yResult = start + (end - start) * yRand.nextDouble();

        System.out.println("xRand: " + xResult);
        System.out.println("yRand: " + yResult);

        ball.setMove(xResult, yResult);
    }

And here is my setMove method 这是我的setMove方法

    public void setMove(double x, double y){
    dx = x;
    dy = y;
}

Here is how the actual method that moves the ball 这是移动球的实际方法

    public void move(){
    x += dx;
    y += dy;
}

Which is called continuously in this method 在此方法中连续调用

    public void actionPerformed(ActionEvent e) {
    repaint();
    paddle.move();
    ball.move();
}

With my current code, the ball will basically only go in three directions: up, up-left, or left. 按照我当前的代码,球基本上只会朝三个方向:向上,向左或向左。 I've included print lines that are giving random numbers but it seems like it might be rounding off the numbers because it is only going in the three directions. 我已经包含了打印行,这些行提供了随机数,但由于它只在三个方向运行,因此似乎可能会四舍五入数字。

Because of the directions it is going, it seems like it doesn't function with positive numbers, also, when both randomly generated numbers are positive it doesn't move at all. 由于行进方向的原因,它似乎不能与正数一起使用,而且,当两个随机生成的数字均为正数时,它根本不会移动。

Any help would be appreciated, Thanks 任何帮助,将不胜感激,谢谢

I suppose your ball's x and y coordinates are int . 我想你的球的xy坐标是int If you add a double to it, it will round down the result. 如果在其中添加一个double ,它将舍入结果。 That's why your ball moves only to zero or negative directions. 这就是为什么您的球只能向零或负方向移动。

Use float or double for storing the coordinates. 使用floatdouble存储坐标。 When you draw it, you can round them. 绘制时,可以将它们四舍五入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM