Ape Creation Essay | [Game Development Practice - 2D Project 1 - Ruby's Adventure] Controlling the Movement of Game Characters (1-2)

1) User guide

①Foreword
The complete development process of this project has written detailed tutorial documents in the teaching documents of the official Unity project , but because the official documents have been away for a while, there are errors in some places or the readers are using the Unity editor on their own machines. In the process of operation, I still encountered scattered problems, which can no longer correspond to the official tutorial. This blog is a supplement to the projects provided by the official website, as well as personal review and experience sharing.

This series of blogs is derived from the official tutorial, but it will definitely be higher than the official tutorial in the end, allowing readers to integrate the official tutorial and my own sublimation, and be able to independently develop a more complete and feasible game than the official tutorial.
The final development results and resources will also be open sourced on GitHub and Gitee.

②Official tutorial address
[ Official document - 1. Setting up the Unity editor ]
[ Official document - 2. The protagonist and the first script ]
[ Official document - 3. Character controller and keyboard input ]
③How to deal with this series of blogs and the relationship between the official tutorial

My personal suggestion is to first browse the blogs of this series of columns, get a preliminary impression of the precautions and key points, and then follow the official documents to operate step by step.

Because this series of blogs is a revision, supplement, and sublimation of the official tutorial, and the content of this series of blogs will not be particularly lengthy, it will take about 5-7 minutes to read it completely.
If you only look at the content of the article and pay attention to the places that need to be corrected, it will only take about 1 minute.
insert image description here

2) Detailed analysis of specific steps

2.1) "1. Create a new scene" and then add

In the official tutorial, there is no introduction to how to attach the camera after creating a new scene, so it is supplemented to a certain extent.

At this stage, you can also directly use the built-in SampleScene after creating a 2D project to carry out subsequent operations.
insert image description here

In the created MainScene scene, add the following operations:
① Create a new empty game object
Create Empty In the Unity editor, it means to create an empty game object.

Famous Scenes - Object- Oriented Learning

insert image description here

insert image description here
② Add camera components

insert image description here
③ Set the properties on the added Camera component

Mainly adjust the Clear Flags in the Inspector to a solid color Solid Color, and adjust the Projection that controls the projection to an orthographic shape Orthographic, and the others can be kept as default.
insert image description here
Other content and steps can continue to follow the tutorial.
insert image description here

2.2) "9. Declaration Variables" is added

In the official Unity tutorial, the description of the APIs in each Unity is rather vague. The purpose of the tutorial is to let you quickly make a finished product. As for why you need to call these APIs, there is no detailed explanation.

Because I have completed the project initially following the tutorial, and now I am in the stage of review and re-cognition, I will explain the functions of these classes, functions, and variables used in the code as much as possible, so that I can understand them. know why.

① Script- Vector2like
- Vector2
In a 2D scene, this structure can be used to represent positions and vectors. Similarly, when the current scene is 3D, you need to use Vector3.

In this project, it mainly uses its variable x for storing the X component and variable y for storing the Y component to store the position information obtained in 2D coordinates.
insert image description here


② Transform class script API for describing the position, rotation and scaling of objects
- Transform In the Unity editor, the game object added to the scene will be displayed in the Inspector window and a Transform component will be added by default.
insert image description here
In the library provided by Unity, the Transform class is also set to control the component. For this case, the position variable is used.
insert image description here

2.3) "4. Review your script changes" and then add

As mentioned in the tutorial above, the Input Manager page in the Edit -> Project Settings window in the Unity editor lists all the controls that the player can input.
At the same time, in the API provided by Unity, the corresponding Input类function for detecting user input in the editor is also set.

③ Interface for accessing the input system, Input class
script API - Input

insert image description here
In the editor, under the Axes directory where player input can be detected, in the Input class, the GetAxis class is also called to detect whether the player uses Horizontal以及Vertical列表the keys listed below for input operations.

2.4) "11. Expressing Ruby's movement speed in units/second" is added

As explained in the tutorial document, if you directly write the function of calculating up, down, left and right control into the Update function that is called once per frame, and then follow the above calculation logic, if there is a small partner whose computer performance is better, such as 800 frames per second, another The computer performance of a friend is relatively average, such as 30 frames per second. In the same time, the friend with good machine performance has performed 800 position calculations, while the other one is quite miserable.

The picture below is the original words in the official tutorial document, which may be difficult for some friends to read.

insert image description here

其大致思想是这种的:

First, the function that we detect for key input is placed in the Update function, which is called every frame.
Secondly, the frame rate of different machines is different, for example, some 10 frames per second, then a frame takes 1/10 of a second; some 60 frames per second, then each frame will take 1/60 of a second.
Then, no matter how many frames the different machines have, the final calculation is the distance generated by 1 second * speed.
Because Update is called according to the frame, 60 frames is called 60 times, and the distance calculated for each frame is the speed * the interval time of each frame (Time.deltaTime),
总的计算式就是 60 * 速度 * 1/60 = 速度 * 1秒

④ The interface for obtaining time information from Unity, the Time class
scripting API - Time
can use it 静态变量deltaTime计算从上一帧到当前帧的时间间隔to solve the above problems.
Then I will not put the code recommended in the official documentation here, I believe everyone has followed it. Now we want to improve the document, when the vertical and horizontal control buttons are pressed at the same time, the speed superimposition occurs.
For the reasons for speed stacking, you can refer to part of this article:
A developer's self-learning road (7) - the movement of characters in Unity3d

In order to avoid this kind of speed superposition, a more unified solution is to use标准化

//游戏角色的移动速度,开放为public,可以在Unity编辑器中进行设置
    public float speed =4.0f;
    //声明一个2D的刚体变量,用于存放游戏角色对象
    Rigidbody2D _rigidbody2d;
    //水平输入
    float _inputX;
    //垂直输入
    float _inputY;

    // Start is called before the first frame update
    void Start()
    {
        //返回Rigidbody2D类型的组件
        //务必已经在Ruby游戏对象上挂接Rigidbody2D组件
        _rigidbody2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        /*
         * GetAxisRaw不使用平滑滤波器
         * 就是说GetAxis可以返回-1到1之间的数,比如检测到按键按下的时候,由0不断增加过渡到1
         * GetAxisRaw只能返回-1,0,1三个值!
         */
        _inputX = Input.GetAxisRaw("Horizontal");
        _inputY = Input.GetAxisRaw("Vertical");
		
        Vector2 input = new Vector2(_inputX, _inputY).normalized;
        _rigidbody2d.velocity = input * speed;
        
    }

⑤ Rigidbody physics components for 2D sprites, Rigidbody2D
scripting API - Rigidbody2D
After adding Rigidbody2D components to sprites, its motion will be controlled by the physics engine. This means that the sprite will be affected by gravity and can be controlled using forces in the script. By adding appropriate collider components, sprites can also respond to collisions with other sprites.
The Rigidbody2D class provides basically the same functionality as the Rigidbody class, with the difference that Rigidbody2D is used in 2D environments and Rigidbody is used in 3D environments.

⑥ Used to return the game object that hooks the Rigidbody2D component, GetComponent
insert image description here

  _rigidbody2d = GetComponent<Rigidbody2D>();

For this line of code, when I hang the Rigidbody2D script on the game character Ruby, after Ruby runs the script and calls the Start function, it returns the Ruby game object.

The above code has a pit that is different from C#. The first reaction to seeing angle brackets <> may be generics, but generics are used to define generic classes , and Getcomponent here is a public function
. Participate in the literature - C# Generic

⑦ Constructor of the Vector2 class representing 2D vectors and points and the variable
Vector2 - The Vector2 constructor
will use the incoming parameters to generate a new vector, and normalized means that the length of the vector can only be at most 1, through this limitation , the speed superposition problem can be solved.
insert image description here

⑧ Indicates the velocity vector of the rigid body, that is, the rate of change of the rigid body position, velocity script API - Rigidbody.velocity

insert image description here

3) Summary

① It is clear that the essence of the movement of the game character object is the change of the position, so we should focus on obtaining the position of the game object and modify its position to write code to realize the character movement.

②Master 速度*时间the way to generate movement, and avoid different running effects due to frame rate.

③ Basic knowledge of the 8 classes, methods, and variables that are often involved in character movement summarized in this article

Guess you like

Origin blog.csdn.net/weixin_52621323/article/details/126584511
Recommended