Unity version-2022.3
切换Input System Package
1.unity默认为Input Manager,需在Editor ->project setting中切换为Input System Package,切换完成后提示需要重启。
2.重启之后在Windows -> Package Manager -> Unity Registry 中安装Input System。
3.为主控节点添加Player Input组件,主控节点一般为空结点,尽量不要将主控脚本挂载玩家模型上。
4.点击Create Actions,创建默认Action文件,注意文件命名,后续需要在C#脚本中引入,我在代码实例中标记了 ①。
5.创建Action文件文件后,在检查器选中Generate C# 类,默认与Action文件同名。
6.打开Action文件,这里的Player对应上一步生成的C#脚本对象中的属性。我在代码实例中标记了②。
上下左右移动控制
- 上下左右移动
- 左右移动实现玩家翻转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem; // 引入 InputSystemPackage ,即Action文件默认生成的类
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 200 ; //默认移动速度
private Rigidbody2D rb; //刚体组件
private PlayerInputControl inputControl; // ①InputSystemPackage生成的脚本文件的类
public Vector2 inputDirection; //记录输入方向
int forwardDirection = 5; //记录面朝方向 ,正为向前,负为向后
void Awake()
{
inputControl = new PlayerInputControl();
rb = GetComponent<Rigidbody2D>(); //获取刚体组件
}
void OnEnable()
{
inputControl.Enable();
}
void Start()
{
}
void Update()
{
//②
inputDirection = inputControl.Player.Move.ReadValue<Vector2>(); //读取用户的输入数据并显示,可以在检查器中实时查看
}
void OnDisable()
{
inputControl.Disable();
}
void FixedUpdate()
{
Translate();
}
private void Translate(){
//实现上下左右移动
rb.velocity = new Vector2(
inputDirection.x * moveSpeed * Time.fixedDeltaTime,
inputDirection.y * moveSpeed * Time.fixedDeltaTime);
//识别输入方向,向右为正,向左为负,无输入即等于零
if(inputDirection.x>0) {
forwardDirection = 5;
}
if(inputDirection.x<0){
forwardDirection = -5;
}
//实现左右移动时翻转
transform.localScale = new Vector3( forwardDirection , 5 , 5 );
}
}
这里要注意移动输入的值最大为1,如果单独一个方向移动则速度为1,如果同时输入两个方向的移动则两个方向的速度都为√2/2,合速度依旧为1。
初学小白学习日志,欢迎指点。