Monday, August 9, 2010

Program to Draw an Animated Bouncing Ball

As I learn to code, programmer friends emphasize that I should break a problem down into chunks that I solve sequentially. It helps me think clearly to focus on one goal at a time.

For example, a recent question asked me to create a ball that bounces within the graphics window, like this.

The 3 main parts of this problem, once you draw the ball, are:

1) Get the ball to MOVE.
2) Get the ball to STOP at the edge of the graphics window.
3) Get the ball to BOUNCE to the next wall, over and over.

Here is how I tackled them:

Step 1. Get the ball to MOVE:
When I started the problem, I just wanted to make a ball on the screen and get it to move in the direction I told it to. It would start moving at an x=y diagonal. I wrote a ‘while’ loop that says, “As long as we’re in this loop, move the ball one pixel to the left (dx) and one pixel down (dy).”

At this point, I didn’t know whether I’d have to tell the loop to make the ball stop moving when it got to the edge of the window or whether it would automatically do so. (Silly me). As it turns out, it really goes on forever! I ran the app to see what would happen, and the ball, once it reached the end of the window, kept going, apparently forever. (See for yourself.) That meant I next had to figure out how to detect the edge of the window and make the ball stop.

Also, the textbook problem required that the ball start off in the middle of the screen, though in my screencast you’ll notice that I had it starting at the top-left corner. This is because, for the Java graphics library, (0,0) is the top-left corner, so it’s easy to start the ball there, whereas placing it in the center requires a trivial bit of algebra that I knew I’d be able to do later. I just wanted to make the ball quickly and confirm that my ‘while’ loop could get the ball to move.

public class BounceBall extends GraphicsProgram {
    public void run() {
   
//First make the ball...    
   GOval ball = new GOval (0, 0, DIAMETER, DIAMETER);
        ball.setFilled(true);
        add(ball);
        
        double dx = 1;
        double dy = 1;
 
        while(true) {
            ball.move(dx, dy);
            pause(PAUSE_TIME);
            
        }
//Private Constants   
    private static final int DIAMETER = 40;
    private static final int PAUSE_TIME = 20;
    }

2) Get the ball to STOP at the edge of the graphics window.

Now I needed to figure out how to make my program “know” when it’s the end of the window, so it could make the ball stop. I wanted the program to say, “When X coordinate of the ball equals the width of the window, or when Y equals the height of the window, stop!” (To be more precise, the X coordinate should actually be the width of the window MINUS the diameter of the ball, so that the ball doesn’t sink past the edge of the window before it bounces each time). 


At first I was stumped, because I couldn’t think of a way to keep track of the x and y coordinates of the ball. After all, in Java, to move the ball, you just declare variables “dx” and “dy”, which tell you how much to move the ball by; you don’t specify what the new coordinates are. After chatting with my friend Emmett, I realized that you could just declare variables “x” and “y” to equal the x and y coordinates of the ball, which you alter, by adding dx and dy to them, respectively, in every iteration of the loop. Indexing x and y lets you check the coordinates, even if it’s not necessary for the “move” command itself. Seems obvious now, so thanks Emmett :) Also in this stage, I centered the ball’s starting position.






public void run() {

//First you make the ball-- centered now
 int x = (getWidth()-DIAMETER)/2; 
 int y = (getHeight()-DIAMETER)/2;    
   
 GOval ball = new GOval (x, y, DIAMETER, DIAMETER); 
 ball.setFilled(true);
 add(ball); 
 
//Then you make it move
 int dx = 1; 
 int dy = 1; 

 while(true) {  
  ball.move(dx, dy);  
  pause(PAUSE_TIME);  
  x += dx; //changing x and y to check coordinates 
  y += dy; //against graphics window    
  
  if (x >= getWidth()-DIAMETER) {    
   break;
      }  
  if (y >= getHeight()+DIAMETER) { 
   break;
      } 
  if (x == 0) {
   break;
     }  
   if (y == 0) {
   break;
     }
}

3) Getting the ball to BOUNCE

Getting the ball to bounce is just a matter of switching the dx or dy variable to its own negative once we detect that the ball hit a wall. (I drew the ball’s path on a notepad before I attempted coding to think this through.) For example, if the ball is moving down and to the right and hits the bottom edge, it will start going upwards, but its horizontal direction will still be to the right. In that case, dy will switch to -dy, but dx won’t change.

What this looks like in terms of coding is I made “if” statements that say, “If we hit the top or bottom of the wall (aka if the y coordinate of the ball is zero or the height of the window), then change dy to -dy. If we hit the right or left side of the window (aka if the x coordinate is zero or the width of the window) then change dx to -dx. This can go on indefinitely.
while(true) {
 ball.move(dx, dy);
    pause(PAUSE_TIME);            
/*Reset the variables x and y at each iteration
 so can check them against window boundaries*/     
    x += dx;
    y += dy;
            
    if (x >= getWidth()-DIAMETER) {
        dx=-dx;
        dy=dy;
            }
    if (y >= getHeight()-DIAMETER) { 
        dx=dx;
        dy=-dy;
            }
    if (x == 0) { 
        dx=-dx;
        dy=dy;
            }
    if (y == 0) {
        dx=dx;
        dy=-dy;
            }
        }


Something to think about is: What will happen if the ball hits a corner? If it hits the top-left corner, will it bounce to straight right or straight down? Answer: it depends on the order you write your “if” statements in. My particular code checks for hitting the left before it checks for the top, so when the ball hits top-left it will bounce horizontally.

28 comments:

  1. Hey Renee,

    Great to see you got this working!

    I thought you might like some words of "wisdom" about this solution ;)

    First off, it works and that's *always* the most important thing - ignore anyone who ever tells you anything different!

    But, having said that, once you've been around the block a few times, code like this will give you a slightly uneasy feeling. Here's why:

    You're keeping track of two variables, x and y in your code. The Ball object is *also* keeping track of those exact same two variables though, internally. Now, this *shouldn't* make you feel uneasy for reasons like "efficiency" - the overhead of maintaining copies of two variables is essentially zero, ignore it.

    The reason it should make you feel uneasy is that, by storing these pieces of information ("state") in two places, you've increased the possibility that you will introduce bugs into your program in the future. What happens, for example, if you add gravity to your program later? Say you do all the calculations to update the Ball's position for gravity, but when making this change, you forget to update your local variables x and y. Then you would have a new bug in the program.

    Always keeping state in only one place is a great way to avoid this type of bug. So how would you do it here? Well, if the Ball object already has getX() and getY() methods, I would use those instead of the local variables x and y. If not, time to crack open the source for the Ball class and add those methods!

    Hope that makes some sense, great to see your programming progress - keep up the great work!

    ReplyDelete
  2. I know this if off topic but I'm looking into starting my own blog and was curious what all is needed to get set up?
    I'm assuming having a blog like yours would cost a pretty penny?
    I'm not very internet savvy so I'm not 100% certain.
    Any recommendations or advice would be greatly appreciated.
    Cheers

    My site; how to get unlimited gems in clash of clans;
    ,

    ReplyDelete
  3. hi!,I love your writing very much! percentage we keep in touch extra approximately your
    article on AOL? I require an expert on this house to resolve
    my problem. May be that's you! Taking a look ahead to look you.



    Also visit my site: biorezonans nedirtbikes

    ReplyDelete
  4. I savor, cause I discovered exactly what I was having a look for.
    You have ended my 4 day long hunt! God Bless you man.
    Have a nice day. Bye

    Visit my website ... fifa 14 unlocked android

    ReplyDelete
  5. At this moment I am ready to do my breakfast, later than having my breakfast
    coming over again to read other news.

    Have a look at my blog post - cigarette electronique

    ReplyDelete
  6. It is, thus, very possible for an established designer to have a freelance design job away from the formal
    employment since all that one needs to do is create a
    website. Hunting for a part-time job online isn't much different to seeking a full-time position; you will encounter the
    same hurdles, and enjoy most of the same benefits, and which ever
    type of job you are looking for, remember to approach it with
    the same level of professionalism and dedication you would a regular job.
    You may enter groups and from there find the connection you
    need to land a good job.

    My web-site :: online jobs work from home - -

    ReplyDelete
  7. It's amazing to pay a visit this website and reading the views of all mates
    about this post, while I am also zealous
    of getting experience.

    My web page :: how to hack garena shells

    ReplyDelete
  8. You really make it seem so easy with your presentation but I
    find this matter to be really something which I think I would never understand.
    It seems too complicated and very broad for me.
    I am looking forward for your next post, I'll try to get
    the hang of it!

    Visit my weblog - A Fazenda

    ReplyDelete
  9. I have been surfing online more than 4 hours today, yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my view, if all site owners and bloggers made good content as you did, the web will
    be a lot more useful than ever before.

    Have a look at my homepage :: smokeless cigarette
    reviews ()

    ReplyDelete
  10. I simply couldn't go away your site before suggesting that I really
    loved the usual information an individual supply to
    your visitors? Is going to be again steadily to check out new
    posts

    my blog: monovision lasik surgery

    ReplyDelete
  11. Keep on working, great job!

    my web page - dragonvale hack tool mac

    ReplyDelete
  12. Way cool! Some extremely valid points! I appreciate you writing this article and also the rest of the site is also very good.


    Also visit my web blog: Christian Louboutin Outlet

    ReplyDelete
  13. Hello there, You have done an incredible job. I'll definitely digg
    it and personally suggest to my friends. I am sure they will be benefited from this web site.


    Here is my webpage: certainly running

    ReplyDelete
  14. Can you tell us more about this? I'd care to find out some additional information.

    Visit mmy weblog ... Game Hacks Archive

    ReplyDelete
  15. Hello! I simply want to give you a huge thumbs up for the great info you have
    got right here on this post. I will be coming back to your
    web site for more soon.

    Here is my site ... Christian Louboutin Heels

    ReplyDelete
  16. Thanks in favor of sharing such a nice thought, piece of writing is nice, thats why i have read it fully

    Feel free to visit my web page ... ethical seo

    ReplyDelete
  17. Nice post. I was checking constantly this blog and I'm impressed!
    Very useful information specially the last part :) I care for such info much.
    I was looking for this particular info for a very long time.
    Thank you and best of luck.

    Here is my weblog: Louis Vuitton Bags

    ReplyDelete
  18. For this reason it is the best to schedule the 3D ultrasound exam after the 25th week of
    pregnancy. Horeover, the designs vary from time to time or it depends on the kind of vehicle you have.
    GTA 5 hack tool is in fact reliable and there's absolutely no
    way of checking account to acquire banned.

    Feel free to visit my website: Telecharger Gta 5 gratuit pc complet

    ReplyDelete
  19. You have a very good point of view here.Yacon Syrup originated
    from a herb located throughout India, Asia and Indonesia and used in Ayurvedic medicines.

    This place appearance is definitely yellow
    and pumpkin shaped. The just about all common list
    for this herb is usually Gambooge. In Asia or throughout additional pieces of the
    planet, this plant is made use of to look after various food as effectively as a preparation for specific foods
    delicancy.

    Here is my weblog: buy yacon root max

    ReplyDelete
  20. Article Writing: Article writing job is excellent for those who have good control of their
    verbs. By taking these steps - learning the basics and building up from there - you've got a better chance than you
    think. Now that you know these important tips you are way ahead of those who are still struggling to achieve internet business success.


    My web blog; ways to earn money

    ReplyDelete
  21. On the chance a plant resides somewhat close to a human population, the concentration of gases may constitute a health hazard, aside from being a
    source of offensively odiferous gases. The water is now potable
    and can be added to existing water supplies, for example reservoirs and dams.
    According to the Board, groundwater in the area is used for both agricultural and
    drinking purposes.

    my blog; replant.co.kr ()

    ReplyDelete
  22. Hi there, I enjoy reading all of your post. I wanted to write a little comment to support you.


    my blog post: goji berry

    ReplyDelete
  23. Hello i am kavin, its my first time to commenting anyplace, when i read this article i thought i could also create comment due to
    this good piece of writing.

    My web blog: nike zoom rookie

    ReplyDelete
  24. Simply wish to say your article is as astounding. The clarity on your post
    is simply excellent and that i could think you're knowledgeable in this subject.
    Well with your permission let me to snatch your RSS feed to keep up
    to date with coming near near post. Thank you a million and please keep up the rewarding work.


    Here is my blog; photo booth ()

    ReplyDelete
  25. I've been browsing online more than 2 hours today, yet I never found any interesting
    article like yours. It is pretty worth enough for me. In my view,
    if all webmasters and bloggers made good content as you did, the internet
    will be a lot more useful than ever before.

    Have a look at my page - Puppy Training Classes New Jersey

    ReplyDelete
  26. Do you mind iff I quote a few of your articles as long as I prvide credit and sources bck to yoir webpage?
    My blog is in the very same area of interest as yours and my users would
    definitely benefit fom some of the ibformation you present here.

    Pleease let me know if this alright with you. Regards!

    Also visit my web site - plants vs zombies hacked

    ReplyDelete
  27. hardiest exist.create wealth At dwelling - Tips To make Your
    cultural Media commercialism? Try These Tricks!
    The Internet can crack more suggestions to wise your attribute and anatomy a right computer
    is not a in particular respectable touch on of adornment and continue the commode treat, and
    so you may typically go by Broyeur
    paysagiste Accueil (korealine.org) Pragma Site familial Eric
    Barrab�� [yagogames.com]��; http://110.50.247.49, Broyeur (http://www.internetpiraten.com/) Emanuele Festival (wikimerda.comli.com)
    Accueil Julien MARTIN
    (www.dumpgames.com)
    E saisie Site familial Eric Barrab��, http://www.mainepcservices.com/forum/profile.php?id=392721, Site familial Eric Barrab�� Your sales legal document countenance you details
    on the abstraction and someone in their favourite
    situation. Your agitate for your scholar. likewise, deliberate exploitation the mental
    object of papers. In this framing, brown is to always spirit for one.
    In the time-consuming run. connect the tips that follows is meant to defend

    ReplyDelete
  28. Kudos forr the fantastic write-up. It provides lokts
    of advice I had been looking for, I will be popping back the future
    to know what you've got to say.

    Also visit my web site: E Juice

    ReplyDelete