Planetalia - Java Training

Training and Consulting

Home

Tutorial - Writing a Space Invaders game in Java

  Previous Page - Cleaning the Screen Current Page - 09 - Controlled movement   Next Page - Flicker
  Return to the index of free Java tutorials  

Controlled movement

(c) Alexander Hristov

Even if it's not apparent, the system we implemented in our previous step to clean the screen before redrawing has a problem which will become clear quite soon. In order to show it, we'll first make the critter move in a more or less controlled way. For example, we can make it move horizontally and "bounce" when it reaches any of the limits of the window. Usually these kinds of movements are implemented introducing a variable vX which will play the role of a "speed" and will store the amount that will be added to the position of the critter in each turn.

If the variable representing the speed is positive, (vX > 0), then the position of the critter will increase and thus it will move to the right. If the variable vX is negative, the X positon will be decreasing and the critter will move to the left.

Controlling the bouncing is done comparing the position of the monster after each movement. If it goes out of the screen from the left (posX < 0 ) or from the right (posX > WIDTH), then the speed must be changed. Using this approach, changing the speed is simply changing the sign of the speed. For example, if before hitting the right wall the value of vX is 5, after hitting it it will become -5 and vice-versa.

All this said, the Java source becomes:


1     package version09;
2     /**
3      * Curso B?sico de desarrollo de Juegos en Java - Invaders
4      * 
5      * (c) 2004 Planetalia S.L. - Todos los derechos reservados. Prohibida su reproducci?n
6      * 
7      * http://www.planetalia.com
8      * 
9      */
10    
11    
12    import java.awt.Canvas;
13    import java.awt.Dimension;
14    import java.awt.Graphics;
15    import java.awt.event.WindowAdapter;
16    import java.awt.event.WindowEvent;
17    import java.awt.image.BufferedImage;
18    import java.net.URL;
19    import java.util.HashMap;
20    
21    import javax.imageio.ImageIO;
22    import javax.swing.JFrame;
23    import javax.swing.JPanel;
24    
25    public class Invaders extends Canvas {
26      public static final int WIDTH = 640;
27      public static final int HEIGHT = 480;
28      public static final int SPEED = 10;
29      
30      public HashMap sprites;
31 public int posX,posY,vX;
32 public BufferedImage buffer; 33 34 public Invaders() { 35 sprites = new HashMap(); 36 posX = WIDTH/2;
37 posY = HEIGHT/2;
38 vX = 2; 39 buffer = new BufferedImage(WIDTH,HEIGHT, BufferedImage.TYPE_INT_RGB); 40 41 JFrame ventana = new JFrame("Invaders"); 42 JPanel panel = (JPanel)ventana.getContentPane(); 43 setBounds(0,0,WIDTH,HEIGHT); 44 panel.setPreferredSize(new Dimension(WIDTH,HEIGHT)); 45 panel.setLayout(null); 46 panel.add(this); 47 ventana.setBounds(0,0,WIDTH,HEIGHT); 48 ventana.setVisible(true); 49 ventana.addWindowListener( new WindowAdapter() { 50 public void windowClosing(WindowEvent e) { 51 System.exit(0); 52 } 53 }); 54 ventana.setIgnoreRepaint(true); 55 ventana.setResizable(false); 56 } 57 58 public BufferedImage loadImage(String nombre) { 59 URL url=null; 60 try { 61 url = getClass().getClassLoader().getResource(nombre); 62 return ImageIO.read(url); 63 } catch (Exception e) { 64 System.out.println("No se pudo cargar la imagen " + nombre +" de "+url); 65 System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage()); 66 System.exit(0); 67 return null; 68 } 69 } 70 71 public BufferedImage getSprite(String nombre) { 72 BufferedImage img = (BufferedImage)sprites.get(nombre); 73 if (img == null) { 74 img = loadImage("res/"+nombre); 75 sprites.put(nombre,img); 76 } 77 return img; 78 } 79 80 public void paintWorld() { 81 Graphics g = buffer.getGraphics(); 82 g.setColor(getBackground()); 83 g.fillRect(0,0,getWidth(),getHeight());
84 g.drawImage(getSprite("bicho.gif"), posX, posY,this); 85 getGraphics().drawImage(buffer,0,0,this); 86 } 87
88 89 public void paint(Graphics g) {} 90 public void update(Graphics g) {} 91 92 93 public void updateWorld() { 94 posX += vX; 95 if (posX < 0 || posX > WIDTH) vX = -vX; 96 } 97 98 public void game() { 99 while (isVisible()) { 100 updateWorld(); 101 paintWorld(); 102 paint(getGraphics()); 103 try { 104 Thread.sleep(SPEED); 105 } catch (InterruptedException e) {} 106 } 107 } 108 109 public static void main(String[] args) { 110 Invaders inv = new Invaders(); 111 inv.game(); 112 } 113 } 114


Do you want to be notified when new tutorials or lessons are published? Press here


Full list of Java source files for this step

Invaders.java      

Full list of resources

bicho.gif bicho0.gif bicho1.gif bicho2.gif
bombD.gif bombDL.gif bombDR.gif bombL.gif
bombR.gif bombU.gif bombUL.gif bombUR.gif
disparo.gif disparo0.gif disparo1.gif disparo2.gif
explosion.wav misil.gif missile.wav musica.wav
nave.gif oceano.gif photon.wav test.gif
Thumbs.db      

  Previous Page - Cleaning the Screen Current Page - 09 - Controlled movement   Next Page - Flicker
  Return to the index of free Java tutorials  

(c) 2004 Planetalia S.L. All rights reserved. Unauthorized reproduction and/or mirroring is not permitted