1. Configuración del entorno Unity
1.1 Descargue los recursos de Unity desde el sitio web oficial: https://unity.cn/releases
1.2 Entorno integrado de Unity Hub, incluida la gestión de herramientas y proyectos
1.3 Editor de unidad
1.4 Editor de secuencias de comandos de Visual Studio 2022
1.5 Herramientas AndroidSKD, JDK, NDK para ejecutar el entorno Android
2. Crear proyecto de Unity
2.1 Crear un nuevo proyecto de plantilla 2D
2.2 Crear un nuevo objeto 2D
2.3 Crear un nuevo archivo de script C#
2.4 Arrastre el archivo de script al área física y asócielo con el objeto
2.5 Haga clic en el script para abrir Visual Studio y editarlo
2.6 Ingrese Debug.Log(gameObject.name); para obtener el nombre del objeto y haga clic para ejecutar
2.7 Depuración, después de guardar el archivo de secuencia de comandos, puede ver que el archivo de secuencia de comandos en UnityEditor cambiará sincrónicamente
2.9 Haga clic en el botón Ejecutar en la parte superior para ver la información de salida del registro en la consola y podrá ver el nombre y la etiqueta del objeto físico impreso.
Tres problemas operativos
3.1 Puede ocurrir un error durante la primera ejecución, lo que indica que el script de Unity muestra "Archivos varios" y no hay ningún mensaje de sintaxis.
3.2 Solución: haga clic en Editar > Preferencias para abrir la ventana de preferencias
3.3 En la ventana de preferencias, seleccione la pestaña Herramientas externas y cambie la configuración del Editor de secuencias de comandos externo a un editor como Visual Studio 2019.
3.4 Puede ver que la gramática se puede mostrar normalmente.
4. Comprender los componentes del objeto
4.1 Una física tiene muchos componentes. Haga clic en la física y aparecerá la información del componente predeterminado.
4.2 Puede agregar nueva información de componentes a la física de la siguiente manera, como agregar nuevos componentes de sonido a los objetos.
4.3 Después de asociar un script con un objeto, también es un componente del objeto. Puede obtener otros componentes del objeto y componentes que controlan el objeto en el script.
4.4 También se pueden crear varios objetos debajo del objeto. Creamos un subobjeto de cápsula y la cápsula pertenece al subcomponente.
4.5 El script obtiene componentes básicos, subcomponentes y componentes principales. Obtenga instancias de objetos y componentes de la siguiente manera:
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
public class main : MonoBehaviour
{
public GameObject Capsule;//胶囊组件
public GameObject Prefab;//预设体
// Start is called before the first frame update
void Start()
{
//拿到当前脚本所挂载的游戏物体
//GameObject go = this.gameObject;
//名称
UnityEngine.Debug.Log(gameObject.name);
//tag
UnityEngine.Debug.Log(gameObject.tag);
//layer
UnityEngine.Debug.Log(gameObject.layer);
//胶囊的名称
UnityEngine.Debug.Log(Capsule.name);
//胶囊当前真正的激活状态
UnityEngine.Debug.Log(Capsule.activeInHierarchy);
//胶囊当前自身激活状态
UnityEngine.Debug.Log(Capsule.activeSelf);
//获取Transform组件
//Transform trans = this.transform;
UnityEngine.Debug.Log(transform.position);
//获取其他组件
BoxCollider bc = GetComponent<BoxCollider>();
//获取当前物体的子物体身上的某个组件
GetComponentInChildren<CapsuleCollider>(bc);
//获取当前物体的父物体身上的某个组件
GetComponentInParent<BoxCollider>();
//添加一个组件
Capsule.AddComponent<AudioSource();
//通过游戏物体的名称来获取游戏物体
//GameObject test = GameObject.Find("Test");
//通过游戏标签来获取游戏物体
GameObject test = GameObject.FindWithTag("Enemy");
test.SetActive(false);
UnityEngine.Debug.Log(test.name);
//通过预设体来实例化一个游戏物体
GameObject go = Instantiate(Prefab, Vector3.zero, Quaternion.identity);
//销毁
Destroy(go);
}
// Update is called once per frame
void Update()
{
}
}
Cinco eventos táctiles y de mouse
5.1 Eventos del mouse
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.Windows;
using Input = UnityEngine.Input;
public class main : MonoBehaviour
{
void Start()
{
}
// Update is called once per frame
void Update()
{
//鼠标的点击
//按下鼠标 0左键 1右键 2滚轮
if (Input.GetMouseButtonDown(0)){
UnityEngine.Debug.Log("按下了鼠标左键");
}
//持续按下鼠标
if (Input.GetMouseButton(0)) {
UnityEngine.Debug.Log("持续按下鼠标左键");
}
//抬起鼠标
if (Input.GetMouseButtonUp(0)) {
UnityEngine.Debug.Log("抬起了鼠标左键");
//按下键盘按键
}
if (Input.GetKeyDown(KeyCode.A)) {
UnityEngine.Debug.Log("按下了A");
}
//持续按下按键
if (Input.GetKey(KeyCode.A)) {
UnityEngine.Debug.Log("持续按下A");
}
//抬起键盘按键
if (Input.GetKeyUp("a")){
UnityEngine.Debug.Log("松开了A");
}
}
}
5.2 Después de guardar y ejecutar, puede ver la salida del registro correspondiente en la consola.
5.3 Teléfono móvil de un solo toque, multitáctil,
using UnityEngine;
using Input = UnityEngine.Input;
public class main : MonoBehaviour
{
void Start()
{
//开启多点触控
Input.multiTouchEnabled = true;
}
// Update is called once per frame
void Update()
{
//判断单点触摸
if (Input.touchCount == 1)
{
//触摸对象
Touch touch = Input.touches[0];//触摸位置
UnityEngine.Debug.Log(touch.position);//触摸阶段
switch (touch.phase)
{
case UnityEngine.TouchPhase.Began:
break;
case UnityEngine.TouchPhase.Moved:
break;
case UnityEngine.TouchPhase.Stationary:
break;
case UnityEngine.TouchPhase.Ended:
break;
case UnityEngine.TouchPhase.Canceled:
break;
}
}
//判断单点触摸
if (Input.touchCount == 2)
{
//触摸对象1
Touch touch0 = Input.touches[0];
//触摸对象1
Touch touch1 = Input.touches[1];
}
}
}
5.4 Movimiento de vectores de objetos, agregando componentes de control de objetos
Movimiento de vector de guión
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlarerControll : MonoBehaviour
{
public CharacterController characterController;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//水平轴
float horizontal = Input.GetAxis("Horizontal");
//垂直轴
float vertical = Input.GetAxis("Vertical");
//创建成一个方向向量
Vector2 dir = new Vector2(horizontal,vertical);
Debug.DrawRay(transform.position, dir, Color.red);
characterController.SimpleMove(dir);
}
}
6. El mouse controla el movimiento de los objetos.
6.1 2D usa el atributo de transformación para controlar el movimiento
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlarerControll : MonoBehaviour
{
public CharacterController characterController;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
//目前的鼠标二维坐标转为三维坐标
Vector2 curMousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
//目前的鼠标三维坐标转为世界坐标
curMousePos = Camera.main.ScreenToWorldPoint(curMousePos);
transform.position = curMousePos ;
}
}
}
6.2 Controlar el movimiento de objetos en Ctrip
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlarerControll : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
StartCoroutine(OnMouseDown());//在Start方法中调用StartCoroutine(要调用的协程方法)
}
// Update is called once per frame
void Update()
{
}
//协程
IEnumerator OnMouseDown()
{
//1. 得到物体的屏幕坐标
Vector3 cubeScreenPos = Camera.main.WorldToScreenPoint(transform.position);
//2. 计算偏移量
//鼠标的三维坐标
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
//鼠标三维坐标转为世界坐标
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
Vector3 offset = transform.position - mousePos;
//3. 物体随着鼠标移动
while (Input.GetMouseButton(0))
{
//目前的鼠标二维坐标转为三维坐标
Vector3 curMousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
//目前的鼠标三维坐标转为世界坐标
curMousePos = Camera.main.ScreenToWorldPoint(curMousePos);
//物体世界位置
transform.position = curMousePos + offset;
yield return new WaitForFixedUpdate(); //这个很重要,循环执行
}
}
}
6.3 Utilice Traducir para deslizar el mouse para moverse
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlarerControll : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// 定义了一个名为sizespeed的公共(public)浮点型(float)变量,初始值为1
public float sizespeed = 1;
// 定义了一个名为mouseSpeed的公共浮点型变量,初始值为10
public float mouseSpeed = 10;
// 定义了一个名为lastMousePosition的私有(private)Vector3类型变量
private Vector3 lastMousePosition;
// Update is called once per frame
void Update()
{
// 获取鼠标滚轮的输入值,并将其赋值给名为mouse的局部(local)浮点型变量
float mouse = -Input.GetAxis("Mouse ScrollWheel");
// 鼠标中键按住拖动
if (Input.GetMouseButton(0))
{
// 获取当前鼠标位置和上一次鼠标位置之间的差值,并将其赋值给名为deltaMousePosition的局部Vector3类型变量
Vector3 deltaMousePosition = Input.mousePosition - lastMousePosition;
// 将摄像机的位置向左右和上下移动,移动的距离由鼠标的移动距离和鼠标速度决定
transform.Translate(deltaMousePosition.x * mouseSpeed * Time.deltaTime, deltaMousePosition.y * mouseSpeed * Time.deltaTime, 0);
}
// 将摄像机的位置向上或向下移动,移动的距离由鼠标滚轮的输入值和大小速度决定
transform.Translate(new Vector3(0, mouse * sizespeed, 0) * Time.deltaTime, Space.World);
// 将鼠标当前位置赋值给lastMousePosition变量,以便下一帧计算鼠标位置差值
lastMousePosition = Input.mousePosition;
}
}
Entendiendo los siete vectores
7.1 El vector es un concepto muy importante en el mundo de los personajes del juego. La mayoría de los objetos anteriores se mueven a través del vector Vector3
7.2 Un vector se refiere a una cantidad que tiene magnitud y dirección. Generalmente se dibuja como un segmento de línea con una flecha (como se muestra a continuación). La longitud del segmento de línea puede representar el tamaño del vector y la dirección del vector es la dirección que señala la flecha. En física, el desplazamiento, la velocidad, la fuerza, etc. son todos vectores.
7.3 Siempre que los vectores tengan la misma magnitud y dirección, se consideran vectores iguales, como se muestra en la siguiente figura. Todos son iguales.
7.4 La suma de vectores se puede explicar mediante tres reglas, como la siguiente regla del triángulo
7.5 La resta de vectores también tiene reglas de operación similares, reglas de triángulos y paralelogramos, recuerda que la flecha siempre apunta del sustraendo al minuendo:
7.6 El vector b sigue siendo un vector cuando se multiplica por un escalar (número real). Observe los siguientes cambios en el vector a cuando cambia el escalar:
Ocho ejemplos, objetos en colisión
8.1 Crear un rol
8.2 Agregue un cuerpo rígido y un cuerpo de colisión al personaje y establezca la gravedad en 0; de lo contrario, se moverá hacia abajo y fuera de la escena.
8.3 Crear un nuevo cuerpo de colisión de obstáculo rojo y también agregar un cuerpo de colisión
8.3 Escribir teclas del teclado en el script para controlar el movimiento de objetos.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyPlayer : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
public float speed = 5f;//移动速度
void Update()
{
float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 0
float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W: 1 S:-1 0
Vector2 position = transform.position;
position.x += moveX * speed * Time.deltaTime;
position.y += moveY * speed * Time.deltaTime;
transform.position = position;
}
}
8.5 Al correr, puedes ver el efecto de detenerte al chocar contra un obstáculo.
8.6 Optimización, se descubre que el personaje se sacudirá y girará cuando encuentre un objeto. Para la rotación, debe verificar el atributo de restricción de rotación del cuerpo rígido del personaje.
8.7 El problema del jitter requiere escribir un guión para reemplazar el movimiento del personaje con el movimiento del cuerpo rígido, la modificación es la siguiente:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyPlayer : MonoBehaviour
{
public Rigidbody2D rbody;
// Start is called before the first frame update
void Start()
{
rbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
public float speed = 10f;//移动速度
void Update()
{
float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 0
float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W: 1 S:-1 0
Vector2 position = rbody.position;
position.x += moveX * speed * Time.deltaTime;
position.y += moveY * speed * Time.deltaTime;
//transform.position = position;
rbody.MovePosition( position);
}
}