Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Bouncing Balls

  1. #1
    Junior Member
    Join Date
    May 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Bouncing Balls

    Hi,
    I found this simple code.
    I am new to threads and i want to know how this code can be modified so that 5balls can be created and bounced off the boundaries.
    Will that require multiple threads - one for each ball?
    Do help me with this. I have been on this since yesterday!


    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Rectangle;
     
    /** An applet that displays a simple animation */
    public class BouncingCircle extends Applet implements Runnable {
      int x = 150, y = 50, r = 50; // Position and radius of the circle
     
      int dx = 11, dy = 7; // Trajectory of circle
     
      Thread animator; // The thread that performs the animation
     
      volatile boolean pleaseStop; // A flag to ask the thread to stop
     
      /** This method simply draws the circle at its current position */
      public void paint(Graphics g) {
        g.setColor(Color.red);
        g.fillOval(x - r, y - r, r * 2, r * 2);
      }
     
      /**
       * This method moves (and bounces) the circle and then requests a redraw.
       * The animator thread calls this method periodically.
       */
      public void animate() {
        // Bounce if we've hit an edge.
        Rectangle bounds = getBounds();
        if ((x - r + dx < 0) || (x + r + dx > bounds.width))
          dx = -dx;
        if ((y - r + dy < 0) || (y + r + dy > bounds.height))
          dy = -dy;
     
        // Move the circle.
        x += dx;
        y += dy;
     
        // Ask the browser to call our paint() method to draw the circle
        // at its new position.
        repaint();
      }
     
      /**
       * This method is from the Runnable interface. It is the body of the thread
       * that performs the animation. The thread itself is created and started in
       * the start() method.
       */
      public void run() {
        while (!pleaseStop) { // Loop until we're asked to stop
          animate(); // Update and request redraw
          try {
            Thread.sleep(100);
          } // Wait 100 milliseconds
          catch (InterruptedException e) {
          } // Ignore interruptions
        }
      }
     
      /** Start animating when the browser starts the applet */
      public void start() {
        animator = new Thread(this); // Create a thread
        pleaseStop = false; // Don't ask it to stop now
        animator.start(); // Start the thread.
        // The thread that called start now returns to its caller.
        // Meanwhile, the new animator thread has called the run() method
      }
     
      /** Stop animating when the browser stops the applet */
      public void stop() {
        // Set the flag that causes the run() method to end
        pleaseStop = true;
      }
    }

    Thanks!


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,145
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Bouncing Balls

    I'd create a Ball class that would paint itself at its location with a timer thread to move it and give it a starting point using a Random number.

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Bouncing Balls

    Quote Originally Posted by roza View Post
    Hi,
    I found this simple code.
    I am new to threads and i want to know how this code can be modified so that 5balls can be created and bounced off the boundaries.
    Will that require multiple threads - one for each ball?
    Do help me with this. I have been on this since yesterday!
    Pretty much what Norm said.

    There is no reason to use multiple threads for this- in fact, there are a few reasons NOT to use multiple threads here! Instead, use a single Swing Timer that updates 5 instances of Ball and calls repaint(). Then in your paint method (if I were you, I'd extend JPanel and override the paintComponent() method instead), just pass the Graphics parameter to each Ball instance- which know how to paint themselves using their own position data.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,145
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Bouncing Balls

    @Kevin - What if you want the balls to move at different speeds? Could that be done by having different changes to the x and y. Would that be jerky?

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Bouncing Balls

    Quote Originally Posted by Norm View Post
    @Kevin - What if you want the balls to move at different speeds? Could that be done by having different changes to the x and y. Would that be jerky?
    Yeah, I'd do that by using different values for delta x and y. It will get jerky if those values get too large, but if you're dealing with more than 25 or so frames a second, I don't see that being an issue because you shouldn't be moving the balls very much between any two frames. Another way to look at it is to update more or less often depending on how fast you want the ball to move- a fast ball might be updated every frame, whereas a slow ball maybe every tenth frame or so (I'd go with different values for x and y though).

    The problem with using multiple threads is that it's more likely that things will look jerky- for example, there's no built-in guarantee that all of the threads will fire at the same rate as each other, or even that one thread will fire at the same rate consistently. You can try to make it work using the Thread.sleep() method, but even that doesn't guarantee that one thread won't fire 5 times, then another thread fires one time, then the first thread fires 10 times, then a third thread fires 100 times...

    I'm being a bit extreme, and you probably CAN do it with multiple threads. But I'd save myself the headache and just use a Timer.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,145
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Bouncing Balls

    Lots of ideas for the OP to think about.
    I wrote it with a Timer for each ball. Fairly simple approach. No difficult logic.
    I'll look at changing it to use a single timer and see how that goes.

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Bouncing Balls

    Quote Originally Posted by Norm View Post
    Lots of ideas for the OP to think about.
    I wrote it with a Timer for each ball. Fairly simple approach. No difficult logic.
    I'll look at changing it to use a single timer and see how that goes.
    Yeah, that should work too (and better than Threads, because I think Timers have a bit of built-in assurances that the firings are fairly uniform). And a lot of this comes down to personal preference- I like to work with only one Timer that controls everything in a game, that way it's easier for me to synchronize everything. But other people might see it differently, so your mileage may vary.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Bouncing Ball Program Random Color Change
    By coderEvolution in forum What's Wrong With My Code?
    Replies: 10
    Last Post: March 3rd, 2011, 04:01 PM

Tags for this Thread