⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 045-052.html

📁 java game programming e-book
💻 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,&nbsp;Macmillan Computer Publishing
    <br>
    <b>ISBN:</b>&nbsp;1571690433<b>&nbsp;&nbsp;&nbsp;Pub Date:</b>&nbsp;11/01/96</font>&nbsp;&nbsp;
</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&#146;ve already seen how to paint masterpieces of art using Java. Now it&#146;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&#146;ll also get a better grasp of the major features of object-oriented programming: objects, inheritance, and dynamic method binding.</P>
<P>Here&#146;s the plan for this chapter. First, you will get a general overview of animation. Then you&#146;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&#146;ll see how to redesign the applet in an object-oriented way that makes it easy to understand, manage, and extend.</P>
<P>Let&#146;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&#146;t move, but it points to the technique that&#146;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>&nbsp;&nbsp;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&#146;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 &#123;
    1. Draw the Current Frame f.
    2. Set f = the Next Frame.
    3. Pause for an interval of time.
&#125;
</PRE>
<!-- END CODE SNIP //-->
<P>Of course, this isn&#146;t Java code, but it captures the essence of computer animation in three steps! You&#146;ll flesh out this loop in the following sections. For now, let&#146;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&#146;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&#146;re limited by the speed of computing resources. A rate of 10&#150;15 fps (equivalent to a pausing interval of around 60&#150;100 milliseconds) gives an adequate illusion of motion, and it&#146;s attainable with Java on most computers. So that&#146;s the frame rate we&#146;ll shoot for in our applets.
</P>
<P>With these concepts in mind, let&#146;s create an animation applet.</P>
<H3><A NAME="Heading3"></A><FONT COLOR="#000077">Creating Our First Animation Applet</FONT></H3>
<P>This applet&#146;s called Broadway Boogie Woogie, with apologies to Mr. Mondrian again! It&#146;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>&nbsp;&nbsp;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&#151;up, down, left, and right&#151;and when a threshold is crossed, the rectangle enters the next state. We&#146;ll use state machines again for defining the behavior of alien ships in your first game.</P>
<P>Let&#146;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 &#123;

  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() &#123;

    System.out.println("&gt;&gt; init &lt;&lt;");
    setBackground(Color.black);
    locx = 80;             // parameters of center rect
    locy = 100;
    width = 110;
    height = 90;
    state = UP;
  &#125;

  public void start() &#123;

    System.out.println("&gt;&gt; start &lt;&lt;");
    animation = new Thread(this);
     if (animation != null) &#123;
       animation.start();
     &#125;
  &#125;

  public void paint(Graphics g) &#123;
    System.out.println("&gt;&gt; paint &lt;&lt;");

    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);
  &#125;

  // update the center rectangle
  void updateRectangle() &#123;
    switch (state) &#123;
    case DOWN:
      locy &#43;= 2;
      if (locy &gt;= 110) &#123;
      state = UP;
      &#125;
      break;
    case UP:
      locy -= 2;
      if (locy &lt;= 90) &#123;
      state = RIGHT;
      &#125;
      break;
    case RIGHT:
      locx &#43;= 2;
      if (locx &gt;= 90) &#123;
      state = LEFT;
      &#125;
      break;
    case LEFT:
      locx -= 2;
      if (locx &lt;= 70) &#123;
      state = DOWN;
      &#125;
      break;

    &#125;

  &#125;

  public void run() &#123;
    while (true) &#123;
      repaint();
      updateRectangle();
      try &#123;
       Thread.sleep (REFRESH_RATE);
      &#125; catch (Exception exc) &#123; &#125;;
    &#125;
  &#125;

  public void stop() &#123;

    System.out.println("&gt;&gt; stop &lt;&lt;");
    if (animation != null) &#123;
      animation.stop();
      animation = null;
    &#125;
  &#125;

&#125;
</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 + -