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

📄 102-107.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:Animating Sprites</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=3//-->
<!--PAGES=102-107//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="100-102.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="107-111.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H3><A NAME="Heading20"></A><FONT COLOR="#000077">Creating an Applet with Bouncing Sprites</FONT></H3>
<P>Here&#146;s the plan for this applet. First, we will derive a BouncingRect from RectSprite. Then, the applet will instantiate a few BouncingRects and run with the standard animation driver. You will see how the Moveable interface is used to set the BouncingRects in motion!
</P>
<P>Take a look at the BouncingRect class, shown in Listing 3-5.</P>
<P><B>Listing 3-5</B> BouncingRect class</P>
<!-- CODE //-->
<PRE>
class BouncingRect extends RectSprite implements Moveable &#123;

  // the coords at which
  //  the rectangle bounces
  protected int max_width;
  protected int max_height;

  // sprite velocity. used to implement Moveable interface
  protected int vx;
  protected int vy;

  public BouncingRect(int x,int y,int w,int h,Color c,
                    int max_w,int max_h) &#123;
    super(x,y,w,h,c);
    max_width = max_w;
    max_height = max_h;
  &#125;

  // implements Moveable interface //
  public void setPosition(int x,int y) &#123;
    locx = x;
    locy = y;
  &#125;

  // implements Moveable interface //
  public void setVelocity(int x,int y) &#123;
    vx = x;
    vy = y;
  &#125;

  // implements Moveable interface //
  // update position according to velocity
  public void updatePosition() &#123;
    locx &#43;= vx;
    locy &#43;= vy;
  &#125;

  // move and bounce rectangle if it hits borders
  public void update() &#123;

    // flip x velocity if it hits left or right bound
    if ((locx &#43; width &gt; max_width) ||
      locx &lt; 0) &#123;
      vx = -vx;
      &#125;

    // flip y velocity if it hits top or bottom bound
    if ((locy &#43; height &gt; max_height) ||
       locy &lt; 0) &#123;
      vy = -vy;
      &#125;
    updatePosition();
  &#125;

&#125;
</PRE>
<!-- END CODE //-->
<P>As promised, BouncingRect provides implementations for the methods specified by Moveable. By calling setPosition() or setVelocity(), you can alter the location or velocity of a BouncingRect object.
</P>
<P>The update() method calculates the new position of the BouncingRect for each frame of the animation. If one of the edges of the rectangle goes beyond the borders, the rectangle bounces by negating the proper component of the velocity. For example, Figure 3-5 illustrates how the rectangle bounces off the right border by flipping the sign of <I>vx</I>.</P>
<P><A NAME="Fig5"></A><A HREF="javascript:displayWindow('images/03-05.jpg',466,399 )"><IMG SRC="images/03-05t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/03-05.jpg',466,399)"><FONT COLOR="#000077"><B>Figure 3-5</B></FONT></A>&nbsp;&nbsp;Rectangle bounce</P>
<P>Now let&#146;s create an applet called Bounce. The initSprites() method of the Bounce applet creates each BouncingRect and sets it in motion by using the Moveable interface. Pay particular attention to the last three lines.
</P>
<!-- CODE //-->
<PRE>
public void initSprites() &#123;

  sprites = new Sprite[NUM_SPRITES]; // init sprite array

  // define sprite for border
  sprites[0] = new RectSprite(0,0,width-1,height-1,Color.green);

  sprites[1] = new BouncingRect(0,0,30,30,Color.yellow,
                             width-1,height-1);

  sprites[2] = new BouncingRect(17,17,13,13,Color.red,
                             width-1,height-1);

  ((Moveable)sprites[1]).setVelocity(4,3);
  ((Moveable)sprites[2]).setVelocity(1,2);
  ((Sprite2D)sprites[2]).setFill(true);  // fill this sprite
&#125;
</PRE>
<!-- END CODE //-->
<P>The last three lines demonstrate how to access interface and subclass methods that aren&#146;t declared in the base abstract class. By casting elements of the <I>sprites</I> array to the appropriate subclass, such as Sprite2D, or interface, such as Moveable,you can access the methods declared there. You will get a compile-time error if you don&#146;t perform these casts, since methods such as setFill() and setVelocity() are not declared in Sprite.</P>
<P>The complete Bounce applet class is shown in Listing 3-6.</P>
<P><B>Listing 3-6</B> Bounce class</P>
<!-- CODE //-->
<PRE>
import java.applet.*;
import java.awt.*;

/////////////////////////////////////////////////////////////////
public class Bounce extends Applet implements Runnable &#123;
  Thread animation;

  Graphics offscreen;
  Image image;

  static final int NUM_SPRITES = 3;
  static final int REFRESH_RATE = 80; // in ms

  Sprite sprites[];                    // sprite array
  int width, height;                   // applet dimensions

  public void init() &#123;
    System.out.println("&gt;&gt; init &lt;&lt;");
    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();
 &#125;

  public void initSprites() &#123;

    sprites = new Sprite[NUM_SPRITES]; // init sprite array

    // define sprite for border
    sprites[0] = new RectSprite(0,0,width-1,height-1,Color.green);

    sprites[1] = new BouncingRect(0,0,30,30,Color.yellow,
                             width-1,height-1);

    sprites[2] = new BouncingRect(17,17,13,13,Color.red,
                               width-1,height-1);

    ((Moveable)sprites[1]).setVelocity(4,3);
    ((Moveable)sprites[2]).setVelocity(1,2);
    ((Sprite2D)sprites[2]).setFill(true);  // fill this sprite
  &#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;

  // CALL EACH SPRITE'S update() METHOD
  // DYNAMIC METHOD BINDING OCCURS HERE!
  public void updateSprites() &#123;
    for (int i=0; i&lt;sprites.length; i&#43;&#43;) &#123;
      sprites[i].update();          // call each sprite's
                                    //    update() method
    &#125;
  &#125;

  // override update so it doesn't erase screen
  public void update(Graphics g) &#123;
    paint(g);
  &#125;

  //
  public void paint(Graphics g) &#123;

    offscreen.setColor(Color.black);
    offscreen.fillRect(0,0,width,height);  // clear buffer

    for (int i=0; i&lt;sprites.length; i&#43;&#43;) &#123;
      sprites[i].paint(offscreen);     // paint each rectangle
    &#125;

    g.drawImage(image,0,0,this);
  &#125;

  public void run() &#123;
    while (true) &#123;
      repaint();
      updateSprites();
      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="100-102.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="107-111.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>


</BODY>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -