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

📄 136-141.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: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,&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=4//-->
<!--PAGES=136-141//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="132-136.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="141-146.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<P>Now let&#146;s write the main applet. We need to provide the mouse handling methods. mouseDown() checks if the mouse gets clicked in the rectangle. If so, <I>set draggable</I>, and save the old mouse position.</P>
<!-- CODE //-->
<PRE>
// if user clicks in the rectangle, make rectangle draggable

int oldx,oldy;    // stores old mouse location
public boolean mouseDown(Event e,int x,int y) {
  if (r.inside(x,y)) {
    oldx = x;
    oldy = y;
    r.setDraggable(true);
  }
  return true;
}
</PRE>
<!-- END CODE //-->
<P>mouseUp() clears <I>draggable</I>:</P>
<!-- CODE SNIP //-->
<PRE>
// if mouseUp, rectangle is no longer draggable
public boolean mouseUp(Event e,int x,int y) {
  r.setDraggable(false);
  return true;
}
</PRE>
<!-- END CODE SNIP //-->
<P>The following method, mouseDrag(), translates the rectangle by the difference between the new mouse position and the old. This makes the rectangle move with the mouse:
</P>
<!-- CODE //-->
<PRE>
// translate the rectangle by the difference between
//   the new mouse position and the old one

public boolean mouseDrag(Event e,int x,int y) {
  if (r.isDraggable()) {
    r.translate(x-oldx,y-oldy);  // move rectangle
    oldx = x;                    // store old mouse position
    oldy = y;
    repaint();                   // redraw screen
  }
  return true;
}
</PRE>
<!-- END CODE //-->
<P>The code to the applet is shown in Listing 4-4. Note that this applet doesn&#146;t implement Runnable, since the actions only occur in response to events. This is an example of <I>event-driven programming. </I>Since this applet&#146;s not double-buffered, you will get flickering, but you know how to cure that!</P>
<P><B>Listing 4-4</B> Draggable Rectangle applet</P>
<!-- CODE //-->
<PRE>
import java.applet.*;
import java.awt.*;

/////////////////////////////////////////////////////////////////
public class Drag extends Applet {
  Font courierFont;
  String testString = "Drag the Rectangle!";
  DragRect r = new DragRect(0,0,107,103,Color.red);

  public void init() {
    courierFont = new Font("Courier",Font.BOLD&#43;Font.ITALIC,14);
  }

  public void paint(Graphics g) {
    g.setFont(courierFont);

    // center the string
    FontMetrics m = g.getFontMetrics();
    int stringWidth = m.stringWidth(testString);
    int width = (bounds().width - stringWidth )/2;
    int height = bounds().height / 2;

    // draw the string
    g.setColor(Color.green);
    g.drawString(testString,width,height);
    r.paint(g);
  }

  // if user clicks in the rectangle, make rectangle draggable
  int oldx,oldy;    // stores old mouse location
  public boolean mouseDown(Event e,int x,int y) {
    if (r.inside(x,y)) {
      oldx = x;
      oldy = y;
      r.setDraggable(true);
    }
    return true;
  }

  // if mouseUp, rectangle is no longer draggable
  public boolean mouseUp(Event e,int x,int y) {
    r.setDraggable(false);
    return true;
  }

  // translate the rectangle by the difference between
  //   the new mouse position and the old one

  public boolean mouseDrag(Event e,int x,int y) {
    if (r.isDraggable()) {
      r.translate(x-oldx,y-oldy);  // move rectangle
      oldx = x;                    // store old mouse position
      oldy = y;
      repaint();                   // redraw screen
    }
    return true;
  }

}
</PRE>
<!-- END CODE //-->
<P>Finally, let&#146;s make the rectangle grow or shrink, depending on input from the keyboard. To do this, you will need to intercept keyboard events.
</P>
<P>First, let&#146;s modify the Draggable Rectangle applet so that the rectangle grows in response to the right arrow key, and shrinks if the left arrow key is down. Add the methods grow() and shrink(), shown in Listing 4-5, to DragRect.</P>
<P><B>Listing 4-5</B> Revisions to DragRect</P>
<!-- CODE //-->
<PRE>
// increase size of rectangle. Note there is no
//    maximum size!
public void grow() {
  width&#43;&#43;;
  height&#43;&#43;;
}

// shrink the rectangle
public void shrink() {
  if (width &gt;  0) {
    width--;
  }
  if (height &gt; 0) {
    height--;
  }
}
</PRE>
<!-- END CODE //-->
<P>Now add the following key handler, shown in Listing 4-6, to the Drag applet.
</P>
<P><B>Listing 4-6</B> Keyboard event handler for Draggable Rectangle applet</P>
<!-- CODE //-->
<PRE>
// Resize rectangle:
// if Right arrow key, grow the rectangle
// if Left arrow key, shrink the rectangle

public boolean keyDown(Event e,int key) {
  switch (key) {
  case Event.RIGHT:
    r.grow();
    repaint();
    break;
  case Event.LEFT:
    r.shrink();
    repaint();
    break;
  default:
    break;
  }
  return true;
}
</PRE>
<!-- END CODE //-->
<P>Just insert these methods into the previous applet, compile, and run!
</P>
<P>Now it&#146;s time to lay the groundwork for our final interactive applet of the chapter. This applet allows you to move a sprite that animates a sequence of bitmaps. To do this, we&#146;ll create a class called BitmapLoop.</P>
<H3><A NAME="Heading18"></A><FONT COLOR="#000077">Creating Bitmap Loops</FONT></H3>
<P>In the previous chapter, you saw how to load, draw, and move a single bitmap. Now let&#146;s create animation by looping a sequence of bitmaps. This requires loading several images, and we&#146;re going to use the MediaTracker class, which is part of java.awt, to do this. Why use MediaTracker? When you execute the following in an Applet,
</P>
<!-- CODE SNIP //-->
<PRE>
Image I;
I = getImage(...);
</PRE>
<!-- END CODE SNIP //-->
<P>the getImage() routine returns immediately with a handle to the Image. However, the requested Image isn&#146;t loaded until it is actually needed, as when a drawImage() takes place. In other words, the process of loading the Image happens asynchronously. And if the Image hasn&#146;t finished loading, drawImage() displays what&#146;s been loaded so far. This is why the bitmap in the Bounce applet looks incomplete at the start of the animation. Clearly, this isn&#146;t desirable in a game! The cure for this is in the MediaTracker class.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading19"></A><FONT COLOR="#000077">Using MediaTracker</FONT></H4>
<P>MediaTracker allows you to wait for the images to finish loading before proceeding with the animation. To use it, first define a MediaTracker object:
</P>
<!-- CODE SNIP //-->
<PRE>
MediaTracker t;
t = new MediaTracker(this);
</PRE>
<!-- END CODE SNIP //-->
<P>Now let&#146;s tell <I>t</I> to track the status of the image sushi.gif. This takes two steps: defining the Image location, and adding the image to the MediaTracker:</P>
<!-- CODE SNIP //-->
<PRE>
Image i = getImage(getCodeBase(),"sushi.gif");
t.addImage(i,0);
</PRE>
<!-- END CODE SNIP //-->
<P>The second argument to addImage() is an ID number. Images of lower ID are loaded first; furthermore, the MediaTracker can wait for images of the same ID to finish loading together.
</P>
<P>To tell MediaTracker to wait for all images to load, use</P>
<!-- CODE SNIP //-->
<PRE>
try {
  t.waitForAll();
}
catch (InterruptedException e) {
{
</PRE>
<!-- END CODE SNIP //-->
<P>To wait for images with ID 13, use
</P>
<!-- CODE SNIP //-->
<PRE>
try {
  t.waitForID(13);
}
catch (InterruptedException e) {
}
</PRE>
<!-- END CODE SNIP //-->
<P>The <I>try-catch</I> construct catches the exception that the MediaTracker object might throw.</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="132-136.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="141-146.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>


</BODY>

⌨️ 快捷键说明

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