Example 1: The actor packman has two sprites asigned which are always shwon one after the other. |
![]() |
// JGameEx8a.java import ch.aplu.jgamegrid.*; public class JGameEx8a extends GameGrid { public JGameEx8a() { super(40, 40, 15); addActor(new Pacman(), new Location(28, 10)); show(); } public static void main(String[] args) { new JGameEx8a(); } } // ------------ class Pacman ----------------------- class Pacman extends Actor { public Pacman() { super(true, "sprites/pacman.gif", 2); } public void act() { move(); if (getNbCycles() % 20 == 0) turn(90); showNextSprite(); } } |
super("sprites/packman.gif", 2); | The number of Sprites is declared in the initialization parameter. If the path to the Sprites is packman.gif,, the two pictures have to have the name packman_0.gif and packman_1.gif and need to be placed inside the directory sprites |
if (idSprite == 0) idSprite = 1 else idSprite = 0 show(idSprite) |
The two sprites are shown one after the other |
Example 2: In this example the actor has 3 differnt Sprites asigned, which are shown in a periodical order. Smooth movements of the actors can be achieved when working inside a grid with a cell size of 1 pixel. The head moves left and right while its phisique changes.
|
![]() |
// JGameEx8.java import ch.aplu.jgamegrid.*; import java.awt.Color; public class JGameEx8 extends GameGrid { public JGameEx8() { super(600, 600, 1); setBgColor(Color.darkGray); addActor(new Head(), new Location(136, 200)); show(); } public static void main(String[] args) { new JGameEx8(); } } // ------------ class Head ----------------------- class Head extends Actor { private double dir = 30; public Head() { super("sprites/head.gif", 3); setDirection(dir); } public void act() { showNextSprite(); if (getX() > 450) { setDirection(180 + dir); } if (getX() < 138) { setDirection(dir); } move(); } } |
super("sprites/head.gif", 3) | The 3 Sprites head_0.gif, head_1.gif and head_2.gif need to be saved inside the directory sprites |
showNextSprite() | simplifies the run through of the Sprites |
This program uses Sprites from the program distribution of the book "Brackeen, Developing Games in Java".