GAMES LESSON SEVENTEEN: Gravity

This sample applet shows a ball bouncing. As with a real ball, the ball bounces a little less high after each bounce until it more or less stops bouncing. This effect is achieved as a result of the use of several variables which keep track of the following things:
  1. y-coordinate (y)
  2. speed (speed)
  3. rate of acceleration (acc)
  4. rate of deceleration (dec)
  5. direction of ball bounce (up)
This applet allows you to re-drop a ball at any time by pressing the ENTER key.

Two important tasks are accomplished in the run method: 1) the value of y is changed, 2) the value of up is changed when necessary. Here is the entire run method:
1 public void run(){ 2 while(true){ 3 if(up){ 4 y-=(int)speed; 5 speed-=dec; 6 } 7 else{ 8 y+=(int)speed; 9 speed+=acc; 10 } 11 if(!up && y>floor-5) up=true; 12 else if(up && y<0) up=false; 13 else if(speed<=0) up=false; 14 repaint(); 15 try{ 16 Thread.sleep(30); 17 }catch(InterruptedException ie){ } 18 } 19 }

Lines three through ten are responsible for changing the value of y. Lines eleven through thirteen change the value of up when necessary.

GRAVITY.java

import java.awt.*; import java.applet.*; import java.util.*; import java.awt.event.*; public class GRAVITY extends Applet implements Runnable{ Dimension d; Image offI; Thread tt; int y; double speed; final static double dec=1.2; final static double acc=.9; boolean up; int floor; public void init(){ d = getSize(); floor = d.height-20; reset(); offI=createImage(d.width,d.height); tt = new Thread(this); tt.start(); requestFocus(); this.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent k) { if(k.getKeyCode()==KeyEvent.VK_ENTER){ reset(); } } }); } public void reset(){ y = 0; speed=1; } public void run(){ while(true){ if(up){ y-=(int)speed; speed-=dec; } else{ y+=(int)speed; speed+=acc; } if(!up && y>floor-5) up=true; else if(up && y<0) up=false; else if(speed<=0) up=false; repaint(); try{ Thread.sleep(30); }catch(InterruptedException ie){ } } } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ Graphics offG = offI.getGraphics(); offG.setColor(Color.yellow); offG.fillRect(0,0,d.width,d.height); offG.setColor(Color.blue); offG.fillOval(40,y,10,10); offG.drawLine(0,floor,d.width,floor); g.drawImage(offI, 0,0, this); } }


ASSIGNMENT: