3D Game-Foundation of Discrete Simulation Engine

3D Game-Foundation of Discrete Simulation Engine

GitHub blog address

Short Answer Questions

  • Explain the differences and connections between Game Objects and Assets.

GameObject:

The game object is a component that can accommodate the actual function. The object of the game does nothing by itself. They need special properties to be a role, an environment, or a special effect. Every object does many different things, with proprietary attributes.

Assets:

Resources are representations of any item that can be used in a game or project. Resources can come from files created outside Unity, such as 3d models, audio files, images, or any other type of files supported by Unity. You can also create resource types in Unity, such as animation controllers, audio mixers, or rendering textures.

The links between the two are:

Resources can be used as templates, instantiated into specific game objects, as certain attributes of game objects, and can be used by multiple game objects at the same time.

  • Download several game cases and summarize the structure of resource and object organization (referring to the directory structure of resource and the hierarchy structure of game object tree)

    Download a simple game in GitHub- Aircraft Wars

    Game resource structure:

    The content of game resources is divided into audio, script, image and so on. According to the different types of files, these resources are added to different folders to form a tree structure. The following picture:

Game Object Structure:

The game classifies the game objects according to their roles and adds them to different folders according to their functions to form a tree structure. The following picture:

  • Write a code that uses the debug statement to verify the basic behavior of MonoBehaviour or the condition of event triggering

    • The basic behavior includes Awake() Start() Update() FixedUpdate() LateUpdate()
    • Common events include OnGUI (), OnDisable (), OnEnable ()
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class NewBehaviourScript : MonoBehaviour {
    
        void Awake()
        {
            Debug.Log("This is Awake!");
        }
    
        void Start()
        {
            Debug.Log("This is Start!");
        }
    
        void Update()
        {
            Debug.Log("This is Update!");
        }
    
        void FixedUpdate()
        {
            Debug.Log("This is FixedUpdate!");
        }
    
        void LateUpdate()
        {
            Debug.Log("This is LateUpdate!");
        }
    
        void OnGUI()
        {
            Debug.Log("This is OnGUI!");
        }
    
        void OnDisable()
        {
            Debug.Log("This is OnDisable!");
        }
    
        void OnEnable()
        {
            Debug.Log("This is OnEnable!");
        }
    
    }
    
    

    Operation results:

    Event name Conditions or timing of implementation
    Awake Awake is called when a script instance is loaded. Or call it when the script is constructed
    Start Called the first time you enter the game loop
    FixUpdate Each game cycle, called by the physical engine
    Update After all Start calls are completed, they are called by the game loop
    LastUpdate After all the Update calls are completed, they are called by the game loop
    OnGUI The game loop is called after the scene is rendered during the rendering process.
    OnEnable Called when an object becomes available or active
    OnDisable Called when an object becomes unavailable or inactive
  • Find script manuals and learn about GameObject, Transform, Component objects

    • Translation of official descriptions of three objects

      GameObject: GameObjects are the fundamental objects in Unity that represent characters, props and scenery. They do not accomplish much in themselves but they act as containers for Components, which implement the real functionality.

      GameObject is the basic object representing game roles, props and scenes in the unity. They don't do much work by themselves, but they act as containers for components that implement real functions.

      Transform: The Transform is used to store a GameObject's position, rotation, scale and parenting state and is thus very important. A GameObject will always have a Transform component attached - it is not possible to remove a Transform or to create a GameObject without one.

      Transform is used to store the location, rotation, scaling, and state of the parent element of GameObject, so it is very important. Each GameObject has a Transform component that cannot be deleted and cannot create a GameObject without Transform.

      Component: Components are the nuts & bolts of objects and behaviors in a game. They are the functional pieces of every GameObject.

      Component s are nuts and bolts for objects and actions in the game. They are the functional parts of each game object.

    • Describe the attributes of the table object (entity) in the following figure, the attributes of the table's Transform, and the components of the table

      • The requirement of this topic is to match the visual graphical programming interface with the Unity API. When you are on the Inspector panel, you should know the corresponding API.
      • For example, the object of table is GameObject, and the first selection box is the activeSelf attribute.

      The object of table is GameObject. Its attributes are layer (layer, Default), scene (scene), tag (tag, untagged), etc.
      Transform property of table: position at (0, 0, 0), rotation parameter (0, 0, 0), scaled to initial value (1, 1, 1).
      The components of table are: Tranform, Cube(Mesh Filter), Box Collider, Mesh Renderer.

    • Describe the relationship between the three using UML diagrams (use UMLet 14.1.1 stand-alone version to map)

  • Collate relevant learning materials and write simple code to verify the implementation of the following technologies:

    The directory structure of the current project is:

    • Find objects

      Find GameObject code named zwk1:

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class NewBehaviourScript : MonoBehaviour
      {
      
          // Use this for initialization
          void Start()
          {
      
              var cube = GameObject.Find("zwk1");
      
              if (cube != null)
              {
                  Debug.Log("Find zwk1!");
              }
              else
              {
                  Debug.Log("There is no zwk1!");
              }
      
          }
      
          // Update is called once per frame
          void Update()
          {
      
          }
      }
      

      Operation results:

    • Adding child objects

      Add a cube code named zwk3:

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class NewBehaviourScript : MonoBehaviour
      {
      
          // Use this for initialization
          void Start()
          {
              GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
              cube.name = "zwk3";
              cube.transform.position = new Vector3(0, Random.Range(0, 3), 0);
              cube.transform.parent = this.transform;
          }
      
          // Update is called once per frame
          void Update()
          {
      
          }
      }
      

      Operation results:

      (Note: zwk3 only appears at runtime and disappears automatically after stopping running)

    • Traversing Object Tree

      Code:

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class NewBehaviourScript : MonoBehaviour
      {
      
          // Use this for initialization
          void Start()
          {
              foreach (Transform child in transform)
              {
                  Debug.Log(child.name);
              }
          }
      
          // Update is called once per frame
          void Update()
          {
      
          }
      }
      

      Operation results:

    • Clear all child objects

      Code:

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class NewBehaviourScript : MonoBehaviour
      {
      
          // Use this for initialization
          void Start()
          {
              foreach (Transform child in transform)
              {
                  Destroy(child.gameObject);
              }
          }
      
          // Update is called once per frame
          void Update()
          {
      
          }
      }
      

      Operation results:

      (Note: zwk1 and zwk2 only disappear at runtime and appear after stopping running)

  • Resource Prefabs and Clone

    • What are the benefits of Prefabs?

      It makes a template of the objects that need to be used. It can be placed in multiple scenarios or multiple times in one scenario.
      As long as the prototype of Prefabs changes, all Prefabs instances will change, suitable for batch processing.

    • What is the relationship between presupposition and clone or copy or Instantiate of Unity Object?
      Cloning copies the existing game objects and presuppositions, which are independent and non-interfering with each other, that is, cloning is not affected by the cloned objects.

      If the default is modified, all game objects instantiated by the default will be changed.

    • Make table prefabrication, write a piece of code to instantiate table prefabricated resources into game objects

      First, make a Table prefabrication and put it in Resources.

      The prefabricated resource instantiation code is as follows:

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class NewBehaviourScript : MonoBehaviour
      {
          public GameObject Table;
          // Use this for initialization
          void Start()
          {
              GameObject cube1 = Instantiate(Resources.Load("Table") as GameObject);
          }
      
          // Update is called once per frame
          void Update()
          {
      
          }
      }
      

      Drag and drop C#script onto camera and click Run.

      Operation results:

      (before operation)

      (in operation)

Programming Practice, Games

  • Game content: Jingzi or loan calculator or simple calculator, etc.

  • Technical limitations: Only IMGUI is allowed to build UI

  • Operational purposes:

    • Understanding OnGUI() events to enhance debug capabilities

    • Improve the ability to read API documents

      Game design ideas:

      Background images are loaded in Awake behavior.

      Initialize in the start behavior (call the Reset() function).

      In OnGUI, the appearance of background picture and related font buttons is first set up. Then set the event of clicking the button. Click on the [reset] trigger to call the Reset() function; judge the results of the game; click on the blank button to play chess, according to the array of 1 or 2 choose to display O or X; Player 1 and Player 2 alternately play chess.

      The GetResult() function is called in the process of judging the result of the game. The function first checks each row, then each column, and then checks the diagonal line. Finally, if the chessboard is full (count==9) and the winner or loser is still tied.

      Implementation code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class game : MonoBehaviour
{
    private int count = 0;
    private int player = 1;
    private int[,] chess = new int[3, 3];
    //img ----bc
    public Texture2D img;

    void Awake()
    {
        img = (Texture2D)Resources.Load("timg");
    }


    // Use this for initialization
    void Start()
    {
        Reset();
    }

    // Update is called once per frame
    void Reset()
    {
        count = 0;
        player = 1;
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                chess[i, j] = 0;
            }
        }
    }

    private void OnGUI()
    {
        string aa = "";

        //Construct an empty GUIStyle
        GUIStyle bb = new GUIStyle();

        //Setting the bb to display normally is the background picture
        bb.normal.background = img;
        GUI.Label(new Rect(0, 0, 1370, 780), aa, bb);

        //font size, text color, background color of button.
        GUI.skin.button.fontSize = 20;
        GUI.skin.label.fontSize = 30;
        GUI.skin.label.normal.textColor = Color.black;
        GUI.backgroundColor = Color.cyan;

        GUI.Label(new Rect(200, 180, 300, 50), "Player1 -- O");
        GUI.Label(new Rect(200, 230, 300, 50), "Player2 -- X");

        //press [reset] button.
        if (GUI.Button(new Rect(500, 400, 100, 50), "Reset"))
        {
            Reset();
        }

        //get results (if any) ---3 conditions.
        int result = GetResult();
        if (result == 1)
        {
            GUI.Label(new Rect(510, 20, 100, 50), "O wins");
        }
        else if (result == 2)
        {
            GUI.Label(new Rect(510, 20, 100, 50), "X wins");
        }
        else if (result == 3)
        {
            GUI.Label(new Rect(530, 20, 200, 50), "Tie!");
        }

        //chess 1---O   2---X
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (chess[i, j] == 1)
                    GUI.Button(new Rect(i * 100 + 400, j * 100 + 80, 100, 100), "O");
                if (chess[i, j] == 2)
                    GUI.Button(new Rect(i * 100 + 400, j * 100 + 80, 100, 100), "X");
                //play chess
                if (GUI.Button(new Rect(i * 100 + 400, j * 100 + 80, 100, 100), "") && result == 0)
                {

                    if (player == 1)
                    {
                        chess[i, j] = 1;
                        player = 2;
                    }
                    else if (player == 2)
                    {
                        chess[i, j] = 2;
                        player = 1;
                    }
                    count++;
                }
            }
        }
    }

    int GetResult()
    {
        //Rows.
        for (int i = 0; i < 3; i++)
        {
            if (chess[i, 0] == chess[i, 1] && chess[i, 0] == chess[i, 2] && chess[i, 0] != 0)
            {
                return chess[i, 0]; //1---O wins
            }
        }

        //Columns.
        for (int j = 0; j < 3; j++)
        {
            if (chess[0, j] == chess[1, j] && chess[0, j] == chess[2, j] && chess[0, j] != 0)
            {
                return chess[0, j]; //2---X wins
            }
        }

        //Diagonals.
        if (chess[0, 0] == chess[1, 1] && chess[0, 0] == chess[2, 2] && chess[0, 0] != 0) return chess[0, 0];
        if (chess[0, 2] == chess[1, 1] && chess[0, 2] == chess[2, 0] && chess[0, 2] != 0) return chess[0, 2];

        //if the game is Tied.
        if (count == 9) return 3;   //tie!
        return 0;
    }
}

Adding background code refers to many blogs on the Internet, and ultimately chooses to use code effects to achieve. First, load the picture, put the picture resource into the new Unity ProjectAssetsResources, and load the picture in Awake.

Operation effect:

Go to Project address Download and run the code.

Thoughts

  • Microsoft XNA engine's Game objects shield the details of the game cycle and use a set of virtual methods to allow successors to complete them. We call this design a "template method pattern".

    • Why is it the "template approach" pattern rather than the "strategy pattern"?

      Policy pattern: The intention is to encapsulate each algorithm into a separate class with a common interface for a set of algorithms, so that they can be replaced by each other. The policy pattern enables the algorithm to change without affecting the client.

      Template method pattern: Define the skeleton of an algorithm in an operation, and defer some steps to a subclass. Template method enables subclasses to redefine some specific steps of the algorithm without changing the structure of an algorithm.

      Popularly, the template method pattern is to design a template for subclasses in order to reuse the methods in subclasses.

      "Game objects shield the details of game loops and use a set of virtual methods to let inheritors complete them." This means that Game is an abstract class, declaring that some abstract methods enable subclasses to implement the remaining logic. In addition, there may be attributes common to some subclasses in Game. The policy pattern used to encapsulate different algorithms is "interface", which often does not contain attributes. Therefore, we call this design a "template method model".

  • The game object is composed of tree structure, and each node is the game object (or number).

    • Try to explain the Composite Pattern / a design pattern.

      Composite patterns belong to structural patterns, which treat a group of similar objects as a single object. This pattern creates a tree structure of object groups to represent part and whole levels. The key to the realization of composite mode is that simple objects and composite objects must implement the same interface.

    • Use the BroadcastMessage() method to send messages to subobjects. Can you write pseudocode for BroadcastMessage()?

      BroadcastMessage()
      {
      	FOR childObject IN ObjectTree
      		sendMessage();
      }
      
  • A game object uses many components to describe different aspects of its characteristics. We designed Tank game objects not to inherit GameObject objects, but to add a set of Component s to GameObject.

    • What design pattern is this?

      Decorator Pattern

    • Why not design special game objects with inheritance?

      We should try our best to make our code highly cohesive and low coupling.

      If inheritance is adopted, the coupling between components is high, and it is not flexible enough. Decorator can provide more flexibility than inheritance. Decorator can dynamically expand the function of an object (decorate it).

Tags: Unity github Programming calculator

Posted on Tue, 10 Sep 2019 20:44:49 -0700 by PHPFEEDER