📄 045-052.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:Using Objects for Animations</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=2//-->
<!--PAGES=045-052//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="../ch01/041-045.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="052-056.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H2><A NAME="Heading1"></A><FONT COLOR="#000077">Chapter 2<BR>Using Objects for Animation
</FONT></H2>
<P><I>Joel Fan</I></P>
<P><FONT SIZE="+1"><B>Goals:</B></FONT></P>
<P>Understand animation
</P>
<P>Use objects, inheritance, and dynamic method binding to design Java programs</P>
<P>Create animation applets</P>
<P>You’ve already seen how to paint masterpieces of art using Java. Now it’s time to make objects that move and shake on the screen. The process of breathing movement into art and graphics is called <I>animation</I>. Along with learning about animation in this chapter, you’ll also get a better grasp of the major features of object-oriented programming: objects, inheritance, and dynamic method binding.</P>
<P>Here’s the plan for this chapter. First, you will get a general overview of animation. Then you’ll create an animation applet named Broadway Boogie Woogie, and learn about techniques that allow you to improve the appearance and performance of your animations. After that, you’ll see how to redesign the applet in an object-oriented way that makes it easy to understand, manage, and extend.</P>
<P>Let’s talk first about animation.</P>
<H3><A NAME="Heading2"></A><FONT COLOR="#000077">What Is Animation?</FONT></H3>
<P>Back in the olden days, movies were called <I>moving pictures</I>. This quaint term is contradictory, since a single picture can’t move, but it points to the technique that’s used to create the illusion of movement: single pictures, shown in rapid succession. If the difference between consecutive pictures is small enough, your eye is tricked into believing that smooth motion is taking place.</P>
<P>Animation relies on the same technique, except that the pictures are hand-drawn, or computer-drawn, instead of being snapshots of reality. For example, Figure 2-1 shows a sequence of frames that might be used to animate a walking figure, if the frames were cycled one at a time, at a rate of twelve per second.</P>
<P><A NAME="Fig1"></A><A HREF="javascript:displayWindow('images/02-01.jpg',557,379 )"><IMG SRC="images/02-01t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/02-01.jpg',557,379)"><FONT COLOR="#000077"><B>Figure 2-1</B></FONT></A> Animating a walking figure</P>
<P>And though it still takes a team of experts to make the highest-caliber Disney animations, computers make animation easy, since you can easily control what appears on the screen. In fact, the loop shown in Listing 2-1, which we’ll call the Universal Animation Loop, will create animations on any computer.
</P>
<P><B>Listing 2-1</B> Universal Animation Loop</P>
<!-- CODE SNIP //-->
<PRE>
while {
1. Draw the Current Frame f.
2. Set f = the Next Frame.
3. Pause for an interval of time.
}
</PRE>
<!-- END CODE SNIP //-->
<P>Of course, this isn’t Java code, but it captures the essence of computer animation in three steps! You’ll flesh out this loop in the following sections. For now, let’s discuss step 3. As the pausing interval gets shorter, the animation appears smoother, for a given sequence of frames. Equivalently, the greater the number of frames per second, or fps, the better the animation looks. Of course, there’s a natural limit to how many frames per second you can perceive. If the frame rate is too fast, things become a blur. Accordingly, movies display at 24 fps, and that rate would be ideal for computer animation. Unfortunately we’re limited by the speed of computing resources. A rate of 10–15 fps (equivalent to a pausing interval of around 60–100 milliseconds) gives an adequate illusion of motion, and it’s attainable with Java on most computers. So that’s the frame rate we’ll shoot for in our applets.
</P>
<P>With these concepts in mind, let’s create an animation applet.</P>
<H3><A NAME="Heading3"></A><FONT COLOR="#000077">Creating Our First Animation Applet</FONT></H3>
<P>This applet’s called Broadway Boogie Woogie, with apologies to Mr. Mondrian again! It’s an extended version of the applet at the end of Chapter 1, Fundamental Java, except that now the center rectangle boogies about. Figure 2-2 illustrates the boogie action.
</P>
<P><A NAME="Fig2"></A><A HREF="javascript:displayWindow('images/02-02.jpg',462,315 )"><IMG SRC="images/02-02t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/02-02.jpg',462,315)"><FONT COLOR="#000077"><B>Figure 2-2</B></FONT></A> Rectangle boogie</P>
<P>This boogie action is implemented with a simple <I>state machine</I> in updateRectangle(). The rectangle has four states of motion—up, down, left, and right—and when a threshold is crossed, the rectangle enters the next state. We’ll use state machines again for defining the behavior of alien ships in your first game.</P>
<P>Let’s jump right into the code, shown in Listing 2-2. Try to pick out all the places where this applet is different from its predecessor.</P>
<P><B>Listing 2-2</B> Broadway.java</P>
<!-- CODE //-->
<PRE>
import java.applet.*;
import java.awt.*;
public class Broadway extends Applet implements Runnable {
Thread animation;
int locx,locy; // location of rectangle
int width, height; // dimensions of rectangle
static final byte UP = 0; // direction of motion
static final byte DOWN = 1;
static final byte LEFT = 2;
static final byte RIGHT = 3;
byte state; // state the rect is in
// length of pausing interval
static final int REFRESH_RATE = 100; // in ms
// applet methods:
public void init() {
System.out.println(">> init <<");
setBackground(Color.black);
locx = 80; // parameters of center rect
locy = 100;
width = 110;
height = 90;
state = UP;
}
public void start() {
System.out.println(">> start <<");
animation = new Thread(this);
if (animation != null) {
animation.start();
}
}
public void paint(Graphics g) {
System.out.println(">> paint <<");
g.setColor(Color.yellow);
g.fillRect(0,0,90,90);
g.fillRect(250,0,40,190);
g.fillRect(80,110,100,20); // hidden rectangle
g.setColor(Color.blue);
g.fillRect(80,200,220,90);
g.fillRect(100,10,90,80);
g.setColor(Color.lightGray);
g.fillRect(locx,locy,width,height);
g.setColor(Color.red);
g.fillRect(200,0,45,45);
g.fillRect(0,100,70,200);
g.setColor(Color.magenta);
g.fillRect(200,55,60,135);
}
// update the center rectangle
void updateRectangle() {
switch (state) {
case DOWN:
locy += 2;
if (locy >= 110) {
state = UP;
}
break;
case UP:
locy -= 2;
if (locy <= 90) {
state = RIGHT;
}
break;
case RIGHT:
locx += 2;
if (locx >= 90) {
state = LEFT;
}
break;
case LEFT:
locx -= 2;
if (locx <= 70) {
state = DOWN;
}
break;
}
}
public void run() {
while (true) {
repaint();
updateRectangle();
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><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="../ch01/041-045.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="052-056.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
</BODY>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -