📄 146-151.html
字号:
<HTML>
<HEAD>
<META name=vsisbn content="1571690433"><META name=vstitle content="Black Art of Java Game Programming"><META name=vsauthor content="Joel Fan"><META name=vsimprint content="Sams"><META name=vspublisher content="Macmillan Computer Publishing"><META name=vspubdate content="11/01/96"><META name=vscategory content="Web and Software Development: Programming, Scripting, and Markup Languages: Java"><TITLE>Black Art of Java Game Programming:Adding Interactivity</TITLE>
<!-- HEADER --><STYLE type="text/css"> <!-- A:hover { color : Red; } --></STYLE><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"><script><!--function displayWindow(url, width, height) { var Win = window.open(url,"displayWindow",'width=' + width +',height=' + height + ',resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></script><SCRIPT><!--function popUp(url) { var Win = window.open(url,"displayWindow",'width=400,height=300,resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></SCRIPT><script language="JavaScript1.2"><!--function checkForQuery(fm) { /* get the query value */ var i = escape(fm.query.value); if (i == "") { alert('Please enter a search word or phrase'); return false; } /* query is blank, dont run the .jsp file */ else return true; /* execute the .jsp file */}//--></script></HEAD><BODY>
<TABLE border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=75 valign=top>
<img src="../1571690433.gif" width=60 height=73 alt="Black Art of Java Game Programming" border="1">
</td>
<td align="left">
<font face="arial, helvetica" size="-1" color="#336633"><b>Black Art of Java Game Programming</b></font>
<br>
<font face="arial, helvetica" size="-1"><i>by Joel Fan</i>
<br>
Sams, Macmillan Computer Publishing
<br>
<b>ISBN:</b> 1571690433<b> Pub Date:</b> 11/01/96</font>
</td>
</tr>
</table>
<P>
<!--ISBN=1571690433//-->
<!--TITLE=Black Art of Java Game Programming//-->
<!--AUTHOR=Joel Fan//-->
<!--AUTHOR=Eric Ries//-->
<!--AUTHOR=Calin Tenitchi//-->
<!--PUBLISHER=Macmillan Computer Publishing//-->
<!--IMPRINT=Sams//-->
<!--CHAPTER=4//-->
<!--PAGES=146-151//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="141-146.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="151-152.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<P>Let’s put together everything we’ve learned in this chapter. The following applet uses a BitmapLoop to animate a UFO that you can control!
</P>
<H3><A NAME="Heading21"></A><FONT COLOR="#000077">An Interactive Applet Using BitmapLoop Sprites</FONT></H3>
<P>In our final applet of the chapter, you’ll use the BitmapLoop sprite defined above, along with your knowledge of MediaTracker and Java’s event handling. You can use this small applet to animate any series of bitmaps that you’d like to control with the arrow keys. We’ve rigged it up with a sequence of UFO bitmaps, but you can replace them with images of your choice.
</P>
<P>This applet adapts the sprite animation driver that you saw at the end of Chapter 3, Animating Sprites, with two differences:</P>
<DL>
<DD><B>•</B> First, the initSprites() method (which initializes the sprites) now uses MediaTracker to ensure that images are fully loaded before proceeding. The images are stored in the directory image/, which is in the same location as the applet class. The foreground images are named fore0.gif, fore1.gif, …, fore5.gif, and you can load them with a loop that uses String concatenation:
<!-- CODE SNIP //-->
<PRE>
for (int i=0; i<6; i++) {
foreImage[i] = getImage(getCodeBase(),
"image/fore" + i + ".gif");
t.addImage(foreImage[i],0); // add to MediaTracker
}
</PRE>
<!-- END CODE SNIP //-->
<DD><B>•</B> Secondly, this applet overrides the keyDown() method:
<!-- CODE //-->
<PRE>
public boolean keyDown(Event e,int key) {
switch (key) {
case Event.RIGHT:
((Moveable)sprites[0]).setVelocity(3,0);
break;
case Event.LEFT:
((Moveable)sprites[0]).setVelocity(-3,0);
break;
case Event.UP:
((Moveable)sprites[0]).setVelocity(0,-3);
break;
case Event.DOWN:
((Moveable)sprites[0]).setVelocity(0,3);
break;
default:
break;
}
return true;
}
</PRE>
<!-- END CODE //-->
</DL>
<P>This event handler works by comparing <I>key</I> to class variables defined in Event that represent the arrow keys. If an arrow key has been pressed, <I>sprites[0]</I>, which refers to a BitmapLoop, gets cast to Moveable. In this way, you can access the Moveable methods not defined by the Sprite abstract class.</P>
<P>The complete UFOControl applet class is shown in Listing 4-9. We’ve used the UFO animation bitmaps from the next chapter, seen in Figure 5-2, as the foreground bitmap loop, which is stored in files fore0.gif, fore1.gif, .., fore5.gif. The background image is a blue circular halo surrounding the UFO, stored in the file back.gif. Of course, feel free to plug in your own bitmaps!</P>
<P><B>Listing 4-9</B> UFO applet</P>
<!-- CODE //-->
<PRE>
/////////////////////////////////////////////////////////////////
// demo of BitmapLoops and user interaction
/////////////////////////////////////////////////////////////////
import java.applet.*;
import java.awt.*;
public class UFOControl extends Applet implements Runnable {
Thread animation;
Graphics offscreen;
Image image;
static final int NUM_SPRITES = 1;
static final int REFRESH_RATE = 80; // in ms
Sprite sprites[]; // sprite array
int width, height; // applet dimensions
public void init() {
System.out.println(">> init <<");
setBackground(Color.black); // applet background
width = bounds().width; // set applet dimensions
height = bounds().height;
initSprites();
image = createImage(width,height); // make offscreen buffer
offscreen = image.getGraphics();
}
public void initSprites() {
sprites = new Sprite[NUM_SPRITES];
Image backImage; // background Image
Image foreImage[] = new Image[6]; // 6 foreground Images
MediaTracker t = new MediaTracker(this);
backImage = getImage(getCodeBase(),"image/back.gif");
t.addImage(backImage,0);
for (int i=0; i<6; i++) {
foreImage[i] = getImage(getCodeBase(),
"image/fore" + i + ".gif");
t.addImage(foreImage[i],0);
}
System.out.println("loading Images");
// wait for all images to finish loading //
try {
t.waitForAll();
} catch (InterruptedException e) {
return;
}
// check for errors //
if (t.isErrorAny()) {
System.out.println("error");
}
else if (t.checkAll()) {
System.out.println("successfully loaded");
}
// initialize the BitmapLoop
sprites[0] = new BitmapLoop(13,17,backImage,foreImage,this);
}
// Move UFO depending on Arrow Keys
public boolean keyDown(Event e,int key) {
switch (key) {
case Event.RIGHT:
((Moveable)sprites[0]).setVelocity(3,0);
break;
case Event.LEFT:
((Moveable)sprites[0]).setVelocity(-3,0);
break;
case Event.UP:
((Moveable)sprites[0]).setVelocity(0,-3);
break;
case Event.DOWN:
((Moveable)sprites[0]).setVelocity(0,3);
break;
default:
break;
}
return true;
}
public void start() {
System.out.println(">> start <<");
animation = new Thread(this);
if (animation != null) {
animation.start();
}
}
// CALL EACH SPRITE'S update() METHOD
// DYNAMIC METHOD BINDING OCCURS HERE!
public void updateSprites() {
for (int i=0; i<sprites.length; i++) {
sprites[i].update(); // call each sprite's
// update() method
}
}
// override update so it doesn't erase screen
public void update(Graphics g) {
paint(g);
}
//
public void paint(Graphics g) {
offscreen.setColor(Color.black);
offscreen.fillRect(0,0,width,height); // clear buffer
for (int i=0; i<sprites.length; i++) {
sprites[i].paint(offscreen); // paint each rectangle
}
g.drawImage(image,0,0,this);
}
public void run() {
while (true) {
repaint();
updateSprites();
try {
Thread.sleep (REFRESH_RATE);
} catch (Exception exc) { };
}
}
public void stop() {
System.out.println(">> stop <<");
if (animation != null) {
animation.stop();
animation = null;
}
}
}
</PRE>
<!-- END CODE //-->
<P>Run this applet, and use the arrow keys to maneuver the UFO!
</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="141-146.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="151-152.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
</BODY>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -