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

📄 dirmovetest.java

📁 《J2ME Game Programming》随书光盘源代码
💻 JAVA
字号:
import net.jscience.math.kvm.MathFP;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.IOException;

/**
 * A demonstration of moving an on-screen object in an arbitrary direction.
 * @author Martin J. Wells
 */
public class DirMoveTest extends MIDlet implements CommandListener, Runnable
{
   private static int SHIP_FRAME_WIDTH = 16;
   private static int SHIP_FRAME_HEIGHT = 16;
   public static final int FP_PI2 = MathFP.mul(MathFP.PI, MathFP.toFP(2));
   public static final int FP_DEGREES_PER_RAD = MathFP.div(MathFP.toFP(360), FP_PI2);
   public static final int FP_22P5 = MathFP.toFP("22.5");

   private GameScreen myCanvas;
   private Command quit;
   private boolean running;
   private Sprite shipSprite;

   /**
    * A custom canvas class that handles drawing, cycling and input for a basic
    * movement example.
    */
   class GameScreen extends Canvas
   {
      // ship properties
      private int shipXFP;          // x position (as a MathFP)
      private int shipYFP;          // y position (as a MathFP)
      private int direction;        // current direction in degrees

      /**
       * Constructor that sets up the position of the ship.
       */
      public GameScreen()
      {
         shipXFP = MathFP.toFP(50);
         shipYFP = MathFP.toFP(50);
      }

      /**
       * Canvas paint implementation which clears the screen and then draws
       * the ship at its current position.
       * @param graphics The graphics context on which to draw.
       */
      protected void paint(Graphics graphics)
      {
         // Clear the screen.
         graphics.setColor(0);
         graphics.fillRect(0, 0, getWidth(), getHeight());

         // Find the frame corresponding to the current direction by dividing
         // the direction by the increment we each frame in the sprite (360
         // divided by 16 = 22.5) - we use MathFP because of the fractions.
         int frame = MathFP.toInt(MathFP.div(MathFP.toFP(direction), FP_22P5));

         // Set the ship sprite frame to be the one matching the direction.
         shipSprite.setFrame(frame);

         // Draw that frame on the screen.
         shipSprite.draw(graphics, MathFP.toInt(shipXFP), MathFP.toInt(shipYFP));
      }

      /**
       * Moves the ship based on the angle it's facing.
       */
      public void cycle()
      {
         // Move the ship according to its current direction (in radians).
         int dirRadians = MathFP.div(MathFP.toFP(direction), FP_DEGREES_PER_RAD);
         // Add the x component of the movement (cos radians)
         shipXFP = MathFP.add( shipXFP, MathFP.cos(dirRadians) );
         // Add the y component of the movement (negative sin radians). We
         // use negative sin to convert from Cartesian to screen coordinates.
         shipYFP = MathFP.add( shipYFP, -MathFP.sin(dirRadians) );

         // Check our position and wrap around to the other side of the canvas
         // if we have to.
         if (MathFP.toInt(shipXFP) < 0) shipXFP = MathFP.toFP(myCanvas.getWidth()-1);
         if (MathFP.toInt(shipXFP) > myCanvas.getWidth()) shipXFP = MathFP.toFP(0);
         if (MathFP.toInt(shipYFP) < 0) shipYFP = MathFP.toFP(myCanvas.getHeight() - 1);
         if (MathFP.toInt(shipYFP) > myCanvas.getHeight()) shipYFP = MathFP.toFP(0);
      }

      /**
       * React to keys pressed by the user.
       * @param keyCode The code of the key the players pressed.
       */
      protected void keyPressed(int keyCode)
      {
         int action = getGameAction(keyCode);

         // Based on the key they pressed we adjust the facing angle by an
         // increment equal to the facing directions of the ship (16 possible
         // translates to 22.5 which we round up to 23).
         if (action == RIGHT) direction -= 23;
         if (action == LEFT) direction += 23;

         // Wrap the direction around if it's now invalid.
         if (direction < 0) direction = 359-23;
         if (direction > 358) direction = 0;
      }
   }

   /**
    * MIDlet constructor loads up the ship graphics and then creates a
    * cooresponding ImageSet and Sprite. It then constructs a canvas and quit
    * command.
    */
   public DirMoveTest()
   {
      // Load up the standard ship graphics and make up a Sprite.
      try
      {
         Image[] frames = ImageSet.extractFrames(Image.createImage("/ship.png"),
                                                 0, 0, 4, 4,
                                                 SHIP_FRAME_WIDTH, SHIP_FRAME_HEIGHT);
         ImageSet set = new ImageSet(1);
         set.addState(frames, 0);
         shipSprite = new Sprite(set, 0, 0);
      }
      catch (IOException ioe)
      {
         System.out.println("unable to load image");
      }

      // Construct a canvas.
      myCanvas = new GameScreen();

      // And a way to quit.
      quit = new Command("Quit", Command.EXIT, 2);
      myCanvas.addCommand(quit);
      myCanvas.setCommandListener(this);

      running = true;
      Thread t = new Thread(this);
      t.start();
   }

   /**
    * Runnable interface run method that cycles the ship and requests a repaint
    * of the Canvas.
    */
   public void run()
   {
      while (running)
      {
         myCanvas.repaint();
         myCanvas.cycle();

         try
         {
            // Simple timing - sleep for 100 milliseconds.
            Thread.sleep(100);
         }
         catch (InterruptedException e)
         {
         }

      }
   }

   /**
    * Handles Application Manager notification the MIDlet is starting (or
    * resuning from a pause). In this case we set the canvas as the current
    * display screen.
    * @throws MIDletStateChangeException
    */
   protected void startApp() throws MIDletStateChangeException
   {
      Display.getDisplay(this).setCurrent(myCanvas);
   }

   /**
    * Handles Application Manager notification the MIDlet is about to be paused.
    * We don't bother doing anything for this case.
    */
   protected void pauseApp()
   {
   }

   /**
    * Handles Application Manager notification the MIDlet is about to be
    * destroyed. We don't bother doing anything for this case.
    */
   protected void destroyApp(boolean unconditional)
           throws MIDletStateChangeException
   {
   }

   /**
    * The CommandListener interface method called when the user executes
    * a Command, in this case it can only be the quit command we created in the
    * consutructor and added to the Canvas.
    * @param command The command that was executed.
    * @param displayable The displayable that command was embedded within.
    */
   public void commandAction(Command command, Displayable displayable)
   {
      try
      {
         if (command == quit)
         {
            running = false;
            destroyApp(true);
            notifyDestroyed();
         }
      }

      catch (MIDletStateChangeException me)
      {
         System.out.println(me + " caught.");
      }
   }

}

⌨️ 快捷键说明

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