A Unity environment configuration
1.1 Download Unity resources from the official website: https://unity.cn/releases
1.2 Unity Hub integrated environment, including management of tools and projects
1.3 Unity Editor
1.4 Visual Studio 2022 Script Editor
1.5 AndroidSKD, JDK, NDK tools for running the android environment
Two create a Unity project
2.1 Create a new 2D template project
2.2 Create a new 2D object
2.3 Create a new C# script file
2.4 Drag the script file to the physical area and associate it with the object
2.5 Click the script to open Visual Studio for editing
2.6 Enter Debug.Log(gameObject.name); to get the name of the object and click to run
2.7 Debugging, after saving the script file, you can see that the script file in UnityEditor will change synchronously
2.9 Click the run button at the top to see the log output information in the console, and you can see the name and label of the physical object printed out
Three operational problems
3.1 An error may occur during the first run, indicating that the Unity script displays "Miscellaneous Files" and there is no syntax prompt.
3.2 Solution: Click Edit > Preferences to open the preferences window
3.3 In the preferences window, select the External Tools tab and change the settings of the External Script Editor to an editor such as Visual Studio 2019
3.4 You can see that the grammar can be displayed normally
4. Understanding object components
4.1 A physics has many components. Click on the physics and the default component information will appear.
4.2 You can add new component information to physics as follows, such as adding new sound components to objects.
4.3 After a script is associated with an object, it is also a component of the object. You can obtain other components of the object and components that control the object in the script.
4.4 Multiple objects can also be created below the object. We create a capsule sub-object, and the capsule belongs to the sub-component.
4.5 The script obtains basic components, sub-components, and parent components. Obtain object and component instances as follows:
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()
{
}
}
Five mouse and touch events
5.1 Mouse events
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 After saving and running, you can see the corresponding log output on the console.
5.3 Mobile phone single touch, multi-touch,
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 Object vector movement, adding object control components
Script vector movement
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. Mouse controls object movement
6.1 2D uses the transform attribute to control movement
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 Control the movement of objects in 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 Use Translate to slide the mouse to move
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;
}
}
Understanding of seven vectors
7.1 Vector is a very important concept in the game character world. Most of the objects above move through vector Vector3
7.2 A vector refers to a quantity that has both magnitude and direction. It is usually drawn as a line segment with an arrow (as shown below). The length of the line segment can represent the size of the vector, and the direction of the vector is the direction pointed by the arrow. In physics Displacement, velocity, force, etc. are all vectors
7.3 As long as the vectors have the same magnitude and direction, they are considered equal vectors, as shown in the figure below. They are all the same vectors.
7.4 The addition of vectors can be explained by several three rules, such as the following triangle rule
7.5 The subtraction of vectors also has similar operation rules, triangle rules and parallelograms. Remember that the arrow always points from the subtrahend to the minuend:
7.6 Vector b is still a vector when multiplied by a scalar (real number). Observe the following changes in vector a when the scalar changes:
Eight examples, colliding objects
8.1 Create a role
8.2 Add a rigid body and a collision body to the character, and set the gravity to 0, otherwise it will move downward and out of the scene.
8.3 Create a new red obstacle collision body and also add a collision body
8.3 Write keyboard keys in the script to control the movement of objects
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 When running, you can see the effect of stopping when hitting an obstacle.
8.6 Optimization, it is found that the character will shake and rotate when it encounters an object. For rotation, you need to check the rotation constraint attribute of the character's rigid body.
8.7 The jitter problem requires writing a script to replace the movement of the character with the movement of the rigid body. The modification is as follows:
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);
}
}