IPhone game development tutorial game engine (6)

Source: Internet
Author: User

IPhone gamesDevelopment tutorial tourDrama Engine6) This is what I want to introduce. Continue to the previous chapter. This section mainly introducesEventFor more information, see this article.

Solving high-level events

Once you determine the physical actions that a user performs, your code must be able to convert them into forms that can be used by game logic components. How to do this depends on the context of your game, but there are several typical forms:

If a player is ready to control a virtual doll, there is usually continuous interaction between the player and the game. It is often necessary to store the representation of the current user input. For example, if the input device is a remote pole, you may need to record the x-axis and Y-axis coordinates of the current point in the main cycle, and correct the virtual doll momentum. Players and virtual dolls are closely coupled, so the physical state of the controller represents a high-level State model of virtual dolls. When the remote pole moves forward, the virtual doll moves forward. When the "jump" button is pressed, the virtual doll jumps up.

If a player is interacting with a game map, another indirect method is required. For example, a player must touch an object in a game map, and the Code must convert the player's touch coordinates on the screen into the coordinates of the game map to determine what the user has actually touched. This may be simply the offset of the Y axis minus the 2D camera coordinate, or the camera light Collision Detection in 3D scenarios.

Finally, the user may perform some actions that indirectly affect the game, such as suspending the game and interacting with the GUI. At this time, a simple message or function will be triggered to notify the game logic of what to do.

Game Logic

Game logic is a unique part of the game engine. The game logic records the player status and AI status, determines when to reach the destination, and generates all game rules. There are two similar games. Their Image Engine and physical engine may only have slight differences, but their game logic may be quite different.

The game logic works closely with the physical engine. In some games without the physical engine, the game logic is responsible for handling all the physical-related content. However, when there is a game engine in the game engine, make sure that the two are independent. The best way to achieve this is to send high-level game events to the game logic through the physical engine.

High-level Events

The game logic code should try to only deal with high-level problems. It should not deal with the sequence in which the user needs to draw an image to the screen when touching the screen, or whether the two rectangles are intersecting. It should deal with the player's desire to move forward, when a new game object should be created/removed, and what should be done when two objects collide with each other.

To maintain the conceptual distance, code that processes low-level concepts such as user input and physical engines should create high-level messages and send them to the game logic code for processing. This not only ensures code independence and modularity, but also helps debugging. By viewing the logs of high-level message passing, you can determine whether the logic code of the message game is not properly handled), or whether the low-level code of the message is not delivered at the right time ).

A very basic technique for passing high-level messages is to write a String and pass it. If the player presses the up arrow, its virtual doll must move up.

 
 
  1. void onPlayerInput( Input inputEvt ) {     
  2.     if(inputEvt.type == IE_KEY && inputEvt.value == KEY_UP ) {     
  3.         g_myApp->sendGameLogicMessage( "player move forward" );     
  4.     }     
  5. }    

Although the above Code is easy to understand for programmers, it is not efficient for computers. It requires more memory and processing than actually needed. We should use the prompt to replace the user input method. Compared to a string, it uses a "type" and "value ". Since all possible events are structured and limited, we can use integers and enumeration types to display event information in our messages.

First, we define an enumeration type to identify the event type:

 
 
  1. enumeration eGameLogicMessage_Types {     
  2.     GLMT_PLAYER_INPUT,     
  3.     GLMT_PROJECTILE_WEAPON,     
  4.     GLMT_GOAL_REACHED,     
  5. };  

Then we create an enumeration type to identify the event value:

 
 
  1. enumeration eGameLogicMesage_Values {     
  2.     GLMV_PLAYER_FORWARD,     
  3.     GLMV_PLAYER_BACKWARD,     
  4.     GLMV_PLAYER_LEFT,     
  5.     GLMV_PLAYER_RIGHT,     
  6.     GLMV_ROCKET_FIRED,     
  7.     GLMV_ROCKET_HIT,     
  8. };    

Now we define a struct to store our message data:

 
 
  1. view plaincopy to clipboardprint?struct sGameLogicMessage {     
  2.     short type;     
  3.     short value;     
  4. } Message;    

Now, we can use an object to pass our message like the code in the previous example:

 
 
  1. void onPlayerInput( Input inputEvt ) {     
  2.    if(inputEvt.type == IE_KEY && inputEvt.value == KEY_UP ) {     
  3.        Message msg;     
  4.        msg.type = GLMT_PLAYER_INPUT;     
  5.        msg.value = GLMV_PLAYER_FORWARD;     
  6.        g_myApp->sendGameLogicMessage( msg );     
  7.    }     
  8.     

This seems to have done more work, but it runs more efficiently. In the previous example, 20 bytes are used to transmit messages. Each of the 20 characters occupies one byte. Do not forget to terminate the message ). In the second example, only four bytes are used to transmit the same message. But more importantly, when sendGameLogicMessage () is used for processing, it only needs to analyze two switch statements to find the correct response. In the previous example, the Group needs to parse the string, slow speed.

Artificial Intelligence

Another role of game logic is to manage AI agents. Two typical types of games require AI systems: players and computers, and semi-autonomous systems in the gaming world. In both cases, the AI proxy receives input and outputs for the actions of objects in the game world.

In the first type of games, AI is called an expert system. It is expected to be used to simulate the behavior and actions of people who understand the rules of the game, and can adopt different difficult strategies to challenge players. AI has similar input and output to players and can simulate player behavior in a similar way. Because humans are better at processing complex information than today's AI agents, sometimes they provide more input information to expert systems than to players to make AI systems look smarter.

For example, in instant strategy game (RTS), the fog of war is used to restrict players' horizons, but AI enemies can see all units on the map. Although this improves the ability of AI to combat more intelligent players, if the advantage is too large, it will make people feel that AI is cheating. Remember, the important thing about a game is to make players have fun, rather than let AI beat them.

In the second type of games, there may be many AI agents. Every one is independent, and it is not very intelligent. In some cases, AI agents directly face players, and some may be neutral, or even some may be the combination of the first two States.

Some agents may be completely stupid, provide specific, limited behavior, and do not care about what is happening in the game world. An example is the enemy who walks back and forth in the corridor. Some may be a little dumb, with only one input and one output. For example, a player can open or close the door. There are also some very complicated ones that even know how to combine their actions. Choosing the right input for AI agents allows you to mimic "consciousness" and increase reality.

No matter how simple AI agents are, they generally use state machines. For example, in the first example, a completely stupid object must record the direction in which it is moving. A slightly stupid object must record whether it is in an ON or OFF state. More complex objects need to record the "neutral" and "offensive" Action states, such as patrols, confrontation and attacks.

Transparent pause and continue

It is very important to regard a game as a simulation of a major game status. Do not confuse real-world time with game time. If a player decides to take a rest, the game must be suspended. After that, the game must be able to continue smoothly, just as nothing has happened. Because the IPHONE is a mobile device, it is especially important to save and continue the game status.

On the IPHONE, only one application is allowed to run at a time point, and users want these applications to load quickly. At the same time, they want to continue what they did before switching the application. This means that we need the ability to store the game status on the device and continue the game status as quickly as possible. For game development, a task is to maintain the current level and reload it so that players can continue the game even after restarting the application. You need to select which data to save and write it to the disk in a small and stable format. This structured data storage is called serialization.

Depending on the game type, this may be much more difficult than it sounds. For a puzzle game, you only need to record the level at which the player is located and what the scoreboard looks like now. However, in NLP games, you may also need to record the positions of each object in the level in addition to recording the virtual dolls of players. At a specific point in time, this may become difficult to manage, especially when you want it to be completed quickly. In this case, you can take some measures at the game design stage to ensure success.

First, you must decide what to save when saving the game status. The position of each small flame in the flame particle system is not important, but the position of the particle system may be important in Large Games. If they can be obtained from the level data, the status of each enemy in the game may not matter. Further consideration is given in this way. If you can simply start a gamer's virtual doll from the check point, the exact status and position of the player's virtual doll may not need to be saved.

Frame-based logic and time-based logic

Frame-based logic refers to updating game objects based on individual frame changes. Although the time-based logic is more complex, it is more closely related to the actual game status. It is used to update game objects as time passes.

Programmers who are not familiar with game development always make the mistake of mixing frame-based logic with time-based logic. Their differences in definition are subtle, but if they are not handled properly, they will cause very obvious bugs.

For example, let's take player movement as an example. New programmers may write such code:

 
 
  1. void onPlayerInput( Input inputEvent ) {     
  2.     if(inputEvt.type == IE_KEY && inputEvt.value == KEY_UP) {     
  3.         //apply movement based on the user input     
  4.         playerAvatar.y += movementSpeed;     
  5.     }     
  6. }   

Every time a player presses a key, the virtual idol moves a little forward. This is frame-based logic, because every movement change may be accompanied by a new frame. In fact, in this example, each player input event moves. This is more or less like the iteration of the main loop. The impact of movement visualization is only reflected in the next iteration of the main loop. Therefore, virtual doll movement in the middle of any iteration will waste computing. Let's make some improvements:

 
 
  1. void onPlayerInput( Input inputEvent ) {     
  2.     if(inputEvt.type == IE_KEY && inputEvt.value == KEY_UP) {     
  3.         //save the input state, but don't apply it     
  4.         playerAvatar.joystick = KEY_UP;     
  5.     }     
  6.     if(inputEvt.type == IE_KEY_RELEASE) {     
  7.         playerAvatar.joystick = 0;     
  8.     }     
  9. }     
  10. void Update() {     
  11.     //update the player avatar     
  12.     if( playerAvatar.joystick == KEY_UP ) {     
  13.         playerAvatar.y += movementSpeed;     
  14.     }     
  15. }    

Now we know that, when the key is pressed, each game loop will only be given a speed. However, this is still frame-based logic.

The frame-based logic problem is that frame changes do not always occur at the same interval. If rendering or game logic takes more time than usual in a game loop, it may be postponed to the next loop. So, sometimes you need 60 fps), sometimes you only need 30 fps. Because moving is applicable to frames, sometimes you only move at half the normal speed.

You can use time-based logic to accurately express the movement. By recording the time since the last frame update, you can apply partial movement speeds. In this way, you can identify the moving speed in units per second without worrying about the current frame rate. The player's virtual doll speed is consistent:

 
 
  1. void Update( long currTime ) {     
  2.     long updateDT = currTime - lastUpdateTime;     
  3.     //update the player avatar     
  4.     if( playerAvatar.joystick == KEY_UP ) {     
  5.         //since currTime is in milliseconds, we have to divide by 1000     
  6.         // to get the correct speed in seconds.     
  7.         playerAvatar.y += (movementSpeed * updateDT)/1000;     
  8.     }     
  9.     lastUpdateTime = currTime;     
  10. }    

In this example, the total movement speed will be the same, whether it is 2 FPS or 60 FPS. Time-based logic requires a little extra code, but it can make the program more precise without worrying about the temporary delay.

Of course, you can use frame-based logic to develop games. It is important not to mix them. For example, if your graphic Code uses time-based logic to render the mobile animation of a player's virtual doll, but the game logic Code uses the frame-based logic to move it in the game world, in this way, the distance between mobile animations cannot be completely synchronized.

If possible, try to remove the frame-based logic. Time-based logic will be of greater help to you.

Game Logic Structure

The core function of the game logic code is to manage the rules and progress of the game status. Based on your game design, this may mean everything. However, there are still some basic models based on the types of production games.

The game logic is not associated with any specific class, and is displayed in the game status object. When the status of the primary game is initialized, it loads and initializes necessary resources for the level. For example, a group of prompts and words in the game, the picture data of the player's virtual doll, and the picture data of the player's current region. In the game loop, the game logic will accept user input, run physical simulation, and process all collision ending messages, simulate AI actions, and execute game rules. Finally, when the application needs to terminate the primary game status, it releases all game resources and may save the game status to the hard drive.

Depending on the complexity of the game, you may find it easy to further break down the game logic. For example, if you are developing an adventure game, you may have a ground full of environmental data, buildings, rivers, trees, etc) real Player virtual dolls, enemies, non-player roles, switches, and obstacles that can be moved and interacted with players. Various guis enable players to make special actions and display important information in the game world. Each game feature must have a large amount of code. Even if they are combined to form a complete game, you can still maintain their modular work.

You can create a Level Manager class to process the key of the game, including loading and detaching physical and image data displayed in the game world and calling the game engine to detect the collision between the entity and the game world. You can also create another class or some classes to process entities in the game world. Each class loads and unloads the necessary physical and image data for rendering those objects, as well as the AI that controls them.

Finally, you may create another separate class to process user interaction in the game to keep the code independent from the three concepts.

This architecture applies to any type of games. First, evaluate the main features of the game design, and then combine similar functions and data in a certain way.

Summary:

Summary:IPhone gamesDevelopment tutorialGamesEngine 6). I hope this article will help you! You shouldGame EngineThe task that must be completed has a basic understanding. This will help us create these elements in the next section for ourGamesPrepare. Want to learn moreIPhone gamesFor more information about the engine, see the following articles:

IPhone game development tutorial Game Engine 1)

IPhone game development tutorial Game Engine 2)

IPhone game development tutorial Game Engine 3)

IPhone game development tutorial game engine 4)

IPhone game development tutorial game engine 5)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.