简体   繁体   中英

Using randomly generated numbers for animation

I'm trying to recreate pong and I've run into a bug I can't figure out.

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

    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 . If you add a double to it, it will round down the result. That's why your ball moves only to zero or negative directions.

Use float or double for storing the coordinates. When you draw it, you can round them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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