Unity basic notes (2) - Unity2D and input system

Unity2D and input system

Unity2D part

1. Introduction to Unity 2D

1. Concepts of 2D, 3D and UI in games

First, the whole game is generally divided into two parts: UI and game content.

  • UI: User Interface, human-computer interaction, operation interface, generally refers to blood bar, backpack, registration and login in the game.

  • Game content: refers to the display of the actual game world such as scenes and characters.

    Generally, what we call 2D/3D refers to the content of the game. In most cases, the UI itself is 2D.

2. Unity 2D main learning content

(1) 2D material and 2D rendering

(2) 2D physical system

2. The core part of Unity2D: Sprite and SpriteRenderer

1. 2D game camera

2D camera adjustments:

  • Projection can be set to Orthographic, that is, the orthogonal mode (ignoring the distance, losing the 3D features of near and far)

2. Sprite 和 SpriteSheet

  • Sprite : It is a kind of game resource, which represents the picture resource of characters and scenes in 2D games (similar to GameObject in 3D);
  • SpriteSheet : Cut a picture into multiple Sprites, which is SpriteSheet.

Art resources can be used normally after selecting **Sprite(2D and UI)** for the Texture Type property in the Inspector panel. (Click 2D on the scene panel to switch to 2D development perspective)

Pixels Per Unit property: Control the proportion of the sprite sprite, the larger the value, the smaller the sprite and the higher the precision.

Sprite Mode: The mode of the sprite

  • Single: the sprite is a single type, no cutting operation is required

  • Multiple: Sprites are multiple types, and the sprites can be cut and sliced ​​through the Sprite Editor.

  • Polygon

Sprite Editor: sprite editor, need to install 2D Sprite package to use.

  • Slice cutting operation: Automatic automatically analyzes the pixel cutting wizard, Grid By Cell Size cuts according to the grid size ratio, and Grid By Cell Count cuts according to the number of grids (the place without pixels will not be cut)

Generally, the Sprite Sheets sprite set is automatically generated by cutting sprites.

  • Pivot center point, the center point is very important in 2D, it determines how the picture is displayed. If the center point is different, there will be an offset.

3. SpriteRenderer component

The SpriteRenderer component is a component used to display Sprite.

  • Sprite: Indicates the currently displayed Sprite;
  • Color: the color superimposed on Sprite;
  • Flip: Flip, X flips left and right, Y flips up and down;
  • SortingLayer: Sorting layer, used to distinguish the layer sequence of different sprites in 2D games, the lower priority is higher;
  • OrderinLayer: Sorting value, controlling the level of sprites in the same layer.
public class SpriteDemo : MonoBehaviour
{
    private Spriterenderer spriteRenderer;
    public Sprite sprite;
    
    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        spriteRenderer.sprite = sprite;
        spriteRenderer.color = new Color.black;
        spriteRenderer.flipX = true;
    }
}

3. 2D Physical System: Rigid Body

1. Physical system

Unity's physics system mainly simulates physical phenomena in reality, such as gravity.

The commonly used components of the physics system are mainly composed of Rigidbody and Collider .

2. 2D rigid body

If a game wants to have gravity, it must have a RigidBody (rigid body) component.

Properties of the Rigidbody 2D component:
BodyType :

  • Dynamic : dynamic, the most simulated.

  • Kinematic : movement, completely controlled by code.

  • Static : Static, not designed for movement, such as buildings.

Simulated : Whether to simulate, if not simulated, there will be no gravity, collision, etc.

Mass : Mass.

Linear Drag : The drag coefficient for position movement.

Angular Drag : Drag coefficient for rotational movement.

Gravity Scale : Gravity coefficient.

Collision Detection : Collision detection, which defines how to detect collisions between 2D collision bodies.

  • Discrete: If objects move too fast, two objects can overlap or pass through each other.
  • Continuous: GameObjects with 2D Rigidbodies and 2D Colliders do not pass through each other when physics updates, but are more CPU-intensive than Discrete.

Constraints : Defines any constraints on the motion of the 2D rigid body.

  • Freeze Position: divided into X and Y, used to fix the position of the X-axis or Y-axis.
  • Freeze Rotation: Used to fix the rotation of objects, for example, a character standing on the edge cannot allow it to be rotated by gravity.

​ If the sprite needs to move, you need to add a rigid body component, but the rigid body component only pays attention to the physical characteristics of the object itself. It does not care about the collision effect around the object. To make an object contact other objects, you need to use the collision body component.

3. Physical Material

A Physical Material is an asset that is divided into two parts:

  • Friction : Used to set the size of friction.
  • Bounciness : Used to set the bouncy size.
// 刚体组件示例代码
public class RigidbodyDemo : MonoBehaviour
{
    private Rigidbody2D rigidbody2D;
    void Start()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
        rigidbody2D.mass = 3;
        rigidbody2D.gravityScale = 0.5f;
    }
    void Update()
    {
        // 向指定坐标移动
        rigidbody2D.MovePosition(new Vector2(0, 1) * 10);
        // 向指定方向一直移动
        rigidbody2D.MovePosition(transform.position + new Vector3(0, 1, 0) * Time.deltaTime);
        // 改变速度向量,即施加一个任意方向任意大小的速度
        rigidbody2D.velocity = new Vector2(0, 1);
        // 对刚体施加力
        rigidbody2D.AddForce(Vector2.up);
    }
}

4. 2D Physics System: Collider

1. Collider concept

Collider: Refers to the physical edge of a game object in the game , used to prevent model penetration and detect collisions .

2. Collider component

Click Edit Collider in the Inspector panel to edit the collider size in the Scene panel.

  • Offset : offset
  • Size : collider size
  • Material : physical material

3. Collision events

Many times, we need to know the result of collision between two game objects, such as vehicle collision.

  • OnCollisionEnter2D: collision entry, used more
  • OnCollisionExit2D: Collision Exit
  • OnCollisionStay2D: during collision
  • Collision2D: collision information
    • gameObject: the opponent's game object
    • transform

How to enter the collision event?

  1. There is no collider and rigidbody on both sides, it is absolutely impossible to trigger the collision event (function) .
  2. Both sides have colliders and rigidbodies that trigger collision events.
  3. Both sides have colliders, but only one side has a rigid body , and a collision event can also be triggered (no matter which side has a rigid body, a collision event can be triggered).
  4. Both sides have colliders, but neither has a rigid body, and cannot trigger a collision event .

Collision event code example:

// 碰撞进入
private void OnCollisionEnter2D(Collision2D collision)
{
    // print("碰撞进入,碰撞的物体是:" + collision.gameObject.name);
    // 如果碰撞的物体的球,就表示被击中并销毁游戏物体
    if(collision.gameObject.name == "Circle")
    {
        print("被击中");
        GameObject.Destroy(collision.gameObject);
    }
}
// 碰撞退出
private void OnCollisionExit2D(Collision2D collision)
{
    print("碰撞退出");
}
// 碰撞中
private void OnCollisionStay2D(Collision2D collision)
{
    print("碰撞过程中");
}

5. 2D Physics System: Triggering

1. Trigger concept

​ Many times we don't need game objects to collide. For example, in a racing game, we need to know when the player has reached the finish line as a basis for victory or timing. Or the portal, the player can teleport after entering, but these game objects do not need to actually collide with the player .

2. Set the trigger

To set the trigger, you only need to check IsTrigger on the collision body .

Note: After setting the trigger, this game object does not have a "physical edge", and any game object can pass through it.

3. Trigger events

Trigger events are generally used to determine whether two objects have collided and interacted, but there is no need for physical collision effects, such as triggering a plot through a specific location.

  • **OnTriggerEnter2D: **trigger enter
  • **OnTriggerExit2D:** trigger exit
  • **OnTriggerStay2D: ** During the triggering process, it is used more
  • **Collider2D: **The opponent's collision body

How to enter trigger event?

  1. There are no colliders and rigid bodies on both sides, and it is absolutely impossible to trigger events (functions) .
  2. There are colliders and rigidbodies on both sides, and trigger events can occur.
  3. Both sides have colliders, but only one side has rigid bodies , and trigger events can also occur (no matter which side has rigid bodies, trigger events can occur).
  4. Both sides have colliders, but neither has rigidbodies, and trigger events cannot occur .

Unity input system part

1. Game Input Introduction

1. Game Input Concept

The input in the game refers to the player's keyboard keystrokes, mouse clicks and other behaviors.

Generally, some game behaviors are triggered, such as opening backpacks, character movement, etc., the purpose of which is to allow players to interact.

2. Game input scene

PC side: based on keyboard, mouse, joystick and other hardware input;

Tablet/mobile phone: based on screen input, most of the actual responses in the game are UI elements;

Host/Others: based on handles, joysticks;

VR: Based on VR glasses, VR handles, etc.

2. Keyboard input

keyboard input detection

Several situations of keyboard input

  • Keyboard presses:Input.GetKeyDown(KeyCode.A)
  • Button up:Input.GetKeyUp(KeyCode.A)
  • The keyboard is pressed continuously:Input.GetKey(KeyCode.A)

Input method example:

public class KeyboardDemo : MonoBehaviour
{
    private float attackValue = 0;
    void Update()
    {
        #region 按键检测

        // 按下
        // 只有第一次按下的那一帧有效
        if (Input.GetKeyDown(KeyCode.A))
        {
            print("A");
        }

        // 弹起
        // 只有第一次按下的那一帧有效
        if (Input.GetKeyUp(KeyCode.W))
        {
            print("W");
        }

        // 按下中
        // 在按下的过程中持续生效,每一帧都生效
        if (Input.GetKey(KeyCode.S))
        {
            print("S");
        }

        // 蓄力:按下->按住->弹起
        if(Input.GetKeyDown(KeyCode.J))
        {
            print("开始蓄力");
            attackValue = 0;
        }
        if(Input.GetKey(KeyCode.J))
        {
            print("蓄力中");
            attackValue += Time.deltaTime;
        }
        if(Input.GetKeyUp(KeyCode.J))
        {
            print("蓄力结束,攻击力为 " + attackValue);
        }

        #endregion
    }
}

3. Mouse input

mouse input detection

Several cases of mouse input:

  • Mouse down:Input.GetMouseButtonDown(0);
  • Mouse up:Input.GetMouseButtonUp(0);
  • The mouse is pressed continuously:Input.GetMouseButton(0);
  • Current mouse coordinates:Input.mousePosition

​0 represents the left mouse button, 1 represents the right mouse button

Example of mouse input:

public class MouseDemo : MonoBehaviour
{
   void Update()
   {
       // 0:左键,1:右键
       if(Input.GetMouseButtonDown(0))
       {
           print("鼠标左键点击");
       }

       if(Input.GetMouseButtonUp(0))
       {
           print("鼠标左键弹起");
       }

       if(Input.GetMouseButton(0))
       {
           print("鼠标左键持续按下");
       }

       // 鼠标位置
       // 并不是游戏中的位置
       // 而是以左下角为原点,横轴为屏幕宽度,纵轴为屏幕高度的平面直角坐标系
       if (Input.GetMouseButtonDown(1))
       {
           print(Input.mousePosition);

       }
   }
}

4. Detailed explanation of InputManager

1. Introduction to InputManager

InputManager is an input manager provided by Unity for developers . The mouse and keyboard detection we used before are actually inseparable from this.

Access path: Edit->ProjectSettings->InputManager

2. Setting parameters

  • **Name: [the name of the axis] can be directly referenced in script programming. **For example:Input.GetAxis("Horizontal")
  • Nagative Button: [Negative button] This button will send a negative value to the axis.
  • Positive Button: [Forward button] This button will send a positive value to the axis.
  • Gravity: 【Gravity】Enter the speed of reset, only for button/mouse.
  • Dead: [A threshold value] Any input value (whether positive or negative) smaller than this value will be regarded as 0 for the joystick.
  • Sensitivity: [Sensitivity] For keyboard input, the larger the value, the faster the response time, and the smaller the value, the smoother it is. For mouse input, setting this value will scale proportionally to the actual distance the mouse moves.
  • Snap: [Alignment] If this setting is enabled, when the axis receives a reverse input signal, the value of the axis will be immediately set to 0, which is only used for key/mouse input.
  • Invert: 【Reverse】Enabling this parameter allows the forward button to send negative values ​​and the reverse to send positive values.
  • Type【Type】
  • Axis: [Axis] The input axis of the device (joystick, mouse, handle, etc.).
  • JoyNum: 【Joystick Number】Set which joystick to use. The default is to accept all joystick drives. For input shafts and non-keys only.

3. Main method of use

// 有平滑过渡
Input.GetAxis("Horizontal");
// 只能是 -1,0,1
Input.GetAxisRaw("Horizontal");

The default is 0 when there is no input, when there is input:

  • If it is a smooth transition, pressing the negative button will transition from 0 to -1, and pressing the positive button will transition from 0 to 1.
  • If it is GetAxisRaw, press the negative button to get -1, and press the positive button to get 1.

Get input from the mouse wheel:

// 向上滑滚轮为正,向下为负
float wheel = Input.GetAxis("Mouse ScrollWheel");

5. Case

1. Ball movement

(1) Case introduction

Just let the ball move left and right on the platform, A: move to the left, D: move to the right.

(2) Case realization

public class CircleMove : MonoBehaviour
{
    // 每秒移动多少米(常规情况)
    public float Speed = 1;

    // 帧更新
    void Update()
    {
        // 移动
        Move();
    }

    /// <summary>
    /// 移动
    /// </summary>
    void Move()
    {
        // 获取玩家输入状况
        float horizontal = Input.GetAxis("Horizontal");
        //float vertical = Input.GetAxis("Vertical");
        // 根据输入得到移动方向
        Vector3 dir = new Vector3(horizontal, 0, 0);
        // 根据移动方向进行移动,帧率越高 需要 单帧移动速度越低
        transform.Translate(dir * Time.deltaTime * Speed);
    }
}

2. Ball Jump

(1) Function introduction

Based on the movement, the jump function is supplemented: a. The ball will jump up after pressing the space, b. There will be a certain rebound when it lands.

(2) Function realization

public class CircleJump : MonoBehaviour
{
    // 跳跃基于刚体运动
    private new Rigidbody2D rigidbody2D;
    // 跳跃给一个向上的力
    public float JumpPower = 10;
    // 是否在地面上
    private bool isOnGround = true;

    // 在Start()中初始化
    private void Start()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        // 跳跃
        Jump();
    }

    /// <summary>
    /// 跳跃
    /// </summary>
    void Jump()
    {
        // 如果按空格且在地面上就跳跃
        // 防止跳跃给的力可以在空中进行而导致飞天
        if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
        {
            // 因为跳跃是一瞬间执行的和持续性的移动不同
            // 所以不用 Time.deltaTime
            rigidbody2D.AddForce(Vector2.up * JumpPower);
        }
    }

    // 碰撞进入
    private void OnCollisionEnter2D(Collision2D collision)
    {
        // 判断是否接触了地面
        if(collision.gameObject.tag == "Floor")
        {
            isOnGround = true;
        }
    }

    // 碰撞退出
    private void OnCollisionExit2D(Collision2D collision)
    {
        // 判断是否离开地面
        if (collision.gameObject.tag == "Floor")
        {
            isOnGround = false;
        }
    }
}

Guess you like

Origin blog.csdn.net/Dukenone/article/details/126904582