Creating 2D Action Games with the Game API
2004-11-13 22:24
543 查看
Article
Creating 2D Action Games with the Game API
Creating 2D Action Games with the Game API
March 2003 Download: [SimpleGame source code] [muTank source code]
javax.microedition.lcdui.gamepackage. These five classes provide two important capabilities: The new GameCanvasclass makes it possible to paint a screen and respond to input in the body of a game loop, instead of relying on the system's paint and input threads. A powerful and flexible layer API makes it easy to build complex scenes efficiently. Building a Game Loop with GameCanvas GameCanvasis a Canvaswith additional capabilities; it provides methods for immediate painting and for examining the state of the device keys. These new methods make it possible to enclose all of a game's functionality in a single loop, under control of a single thread. To see why this is attractive, think about how you would implement a typical game using Canvas:
run()method, which runs in an application thread, updates the game once each time step. Typical tasks would be to update the position of a ball or spaceship and to animate characters or vehicles. Each time through the loop, repaint()is called to update the screen. The system delivers key events to keyPressed(), which updates the game state appropriately. The problem is that everything's in a different thread, and the game code is confusingly spread over three different methods. When the main animation loop in run()calls repaint(), there's no way of knowing exactly when the system will call paint(). When the system calls keyPressed(), there's no way to know what's going on with the other parts of the application. If your code in keyPressed()is making updates to the game state at the same time the screen is being rendered in paint(), the screen may end up looking strange. If it takes longer to render the screen than a single time step in run(), the animation may look jerky or strange. GameCanvasallows you to bypass the normal painting and key-event mechanisms so that all game logic can be contained in a single loop. First, GameCanvasallows you to access its Graphicsobject directly using getGraphics(). Any rendering on the returned Graphicsobject is done in an offscreen buffer. You can then copy the buffer to the screen using flushGraphics(), which does not return until the screen has been updated. This approach gives you finer control than calling repaint(). The repaint()method returns immeditately and your application has no guarantees about exactly when the system will call paint()to update the screen. GameCanvasalso contains a method for obtaining the current state of the device's keys, a technique called polling. Instead of waiting for the system to call keyPressed(), you can determine immediately which keys are pressed by calling GameCanvas's getKeyStates()method. A typical game loop using GameCanvaslooks like this:
run()method is extremely clean, thanks to GameCanvas.
SimpleGameMIDletto see how it works. You'll see something like a starfish doing calisthenics (perhaps compensating for its missing leg).
Typical 2D action games consist of a background and various animated characters. Although you can paint this kind of scene yourself, the Game API enables you to build scenes using layers. You could make one layer a city background, and another a car. Placing the car layer on top of the background creates a complete scene. Using the car as a separate layer makes it easy to manipulate it independent of the background, and of any other layers in the scene. The Game API provides flexible support for layers with four classes: Layeris the abstract parent of all layers. It defines the basic attributes of a layer, which include a position, a size, and whether or not the layer is visible. Each subclass of Layermust define a paint()method to render the layer on a Graphicsdrawing surface. Two concrete subclasses, TiledLayerand Sprite, should fulfill your 2D game desires. TiledLayeris useful for creati d55a ng background images. You can use a small set of source image tiles to create large images efficiently. Spriteis an animated layer. You supply the source frames and have full control over the animation. Spritealso offers the ability to mirror and rotate the source frames in multiples of 90 degrees. LayerManageris a very handy class that keeps track of all the layers in your scene. A single call to LayerManager's paint()method is sufficient to render all of the contained layers. Using TiledLayer TiledLayeris simple to understand, although it contains some deeper nuances that are not obvious at first glance. The fundamental idea is that a source image provides a set of tiles that can be arranged to form a large scene. For example, the following image is 64 x 48 pixels.
TiledLayerassigns each tile a number, starting with 1 in the upper left corner. The tiles in the source image are numbered as follows:
TiledLayerin code. You need to specify the number of columns and rows, the source image, and the size in pixels of the tiles in the source image. This fragment shows how to load the image and create a TiledLayer.
TiledLayerhas 10 columns and 10 rows. The tiles taken from the image are 16 pixels square. The fun part is creating a scene using these tiles. To assign a tile to a cell, invoke setCell(). You need to supply the column and row number of the cell and the tile number. For example, you could assign tile 5 to the third cell in the second row by calling setCell(2, 1, 5). If these parameters look wrong, please note that the tile index starts at 1, while column and row numbers start at 0. By default, all cells in a new TiledLayerhave a tile value of 0, which means they are empty. The following excerpt shows one way to populate a TiledLayer, using an integer array. In a real game, TiledLayers could be defined from resource files, which would allow more flexibility in defining backgrounds and enhancing the game with new boards or levels.
TiledLayeron the screen, you need to pass a Graphicsobject to its paint()method. TiledLayeralso supports animated tiles, which makes it easy to move a set of cells through a sequence of tiles. For more details, see the API documentation for TiledLayer. Using Sprites for Character Animation The other concrete Layerprovided in the Game API is Sprite. In a way, Spriteis the conceptual inverse of TileLayer. While TiledLayeruses a palette of source image tiles to create a large scene, Spriteuses a sequence of source image frames for animation. All you need to create a Spriteis a source image and the size of each [i]frame. In TiledLayer, the source image is divided into evenly sized tiles; in Sprite, the sub-images are called frames instead. In the following example, a source image tank.png is used to create a Spritewith a frame size of 32 x 32 pixels.
Spritehas a frame sequence that determines the order in which the frames will be shown. The default frame sequence for a new Spritesimply starts at 0 and counts up through the available frames. To move to the next or previous frame in the frame sequence, use Sprite's nextFrame()and prevFrame()methods. These methods wrap around to the beginning or end of the frame sequence. For example, if the Spriteis showing the last frame in its frame sequence, calling nextFrame()will show the first frame in the frame sequence. To specify a frame sequence that is different from the default, pass the sequence, represented as an integer array, to setFrameSequence(). You can jump to a particular point in the current frame sequence by calling setFrame(). There is no way to jump to a specific frame number. You can only jump to a certain point in the frame sequence. Frame changes only become visible the next time the Spriteis rendered, using the paint()method inherited from Layer. Spritecan also transform source frames. Frames may be rotated by multiples of 90 degrees or mirrored, or a combination of both. Constants in the Spriteclass enumerate the possibilities. The Sprite's current transformation can be set by passing one of these constants to setTransform(). The following example mirrors the current frame around its vertical center and rotates it by 90 degrees:
Sprite's reference pixel does not move. By default, the reference pixel of a Spriteis located at 0, 0 in the Sprite's coordinate space, at its upper left corner. When a transformation is applied, the location of the reference pixel is also transformed. The location of the Spriteis adjusted so that the reference pixel stays in the same place. You can change the location of the reference pixel with the defineReferencePixel()method. For many types of animations you will define the reference pixel to be the center of the sprite. Finally, Spriteprovides several collidesWith()methods for detecting collisions with other Sprites, TiledLayers, or Images. You can detect collisions using collision rectangles (fast but sloppy) or at the pixel level (slow but accurate). The nuances of these methods are elusive; see the API documentation for details. The muTank Example The muTank example demonstrates the use of TiledLayer, Sprite, and LayerManager. The important classes are MicroTankCanvas, which contains most of the code, and MicroTankSprite, which encapsulates the behavior of the tank. MicroTankSpritemakes extensive use of transformations. Using a source image with only three frames, MicroTankSpritecan show the tank pointing in any of 16 different directions. Two exposed public methods, turn()and forward(), make the tank easy to control. MicroTankCanvasis a GameCanvassubclass and contains an animation loop in run()that should look familiar to you. The tick()method checks to see if the tank has collided with the board. If so, its last movement is reversed using MicroTankSprite's undo()method. The input()method simply checks for key presses and adjusts the direction or position of the tank accordingly. The render()method uses a LayerManagerto handle painting. The LayerManagercontains two layers, one for the tank, one for the board. The debug()method, called from the game loop, compares the elapsed time through the game loop with the desired loop time (80 milliseconds) and displays the percentage of time used on the screen. It is for diagnostic purposes only, and would be removed before the game was shipped to customers. The timing of the game loop is more sophisticated than in the previous SimpleGameCanvas. To try to perform one iteration of the game loop every 80 milliseconds accurately, MicroTankCanvasmeasures the time it takes to perform tick(), input(), and render(). It then sleeps for the remainder of the 80-millisecond cycle, keeping the total time through each loop as close as possible to 80 milliseconds. Summary MIDP 2.0's Game API provides a framework that simplifies developing 2D action games. First, the GameCanvasclass provides painting and input methods that make a tight game loop possible. Next, a framework of layers makes it possible to create complex scenes. TiledLayerassembles a large background or scene from a palette of source image tiles. Spriteis appropriate for animated characters and can detect collisions with other objects in the game. LayerManageris the glue that holds layers together. The muTank example provides a foundation of working code to demonstrate the Game API. |
相关文章推荐
- Flash™ MX Game Design Demystified: The Official Guide to Creating Games with Flash
- [转]Creating a Data Collector Set with the PLA API
- POJ2996《Help Me with the Game》方法:模拟
- Maximal Square,Given a 2D binary matrix filled with 0's and 1's, find the largest squar
- Learning C++ by Creating Games With UE4(15.05.11)-4(Chapter 8-1)
- Apply Google Map API key (register with the SDK debug certificate)
- POJ2993——Help Me with the Game(字符串处理+排序)
- Creating New DB Using DBCA on 10.2.0.3 Fails With ORA-1092 While Upgrading To The 10.2.0.3 Works Fine
- Create a Brick Breaker Game with the Corona SDK: Collision Detection
- C++ Qt Game Tutorial 2 - Moving With the Arrow Keys
- C++ Qt Game Tutorial 3 - Shooting With the Spacebar
- Play 2D games on Pixel running Android Nougat (N7.1.2) with Daydream View VR headset
- Rewrite MSIL Code on the Fly with the .NET Framework Profiling API
- Write Auto-Updating Apps with .NET and the Background Intelligent Transfer Service API
- Some of the continuous-integration tools that work with Ant (From Ant in Action 2nd Edition)
- The SDK platform-tools version ((21)) is too old to check APIs compiled with API 23
- Creating a Web Control with an Expandable Property in the Designer by Using C#.
- Help Me with the Game(模拟法)
- poj 2996 Help Me with the Game 模拟
- Get Started with the Google Fonts API