Unity-全新版控制角色移动(2D)
本文方法来自b站M_Studio。
第一步:在Edit-Player下滑找到Configuration如图更改。
第二步:Window-Package Manager中搜索input,点击Input System,右侧下载install。
第三步:在Project-Settings中右键-Create-Input Actions(在最下面)。
第四步:双击打开新建的input。第一步点击最左边右上方的加号,第二步更改最右边的参数。第三步选中中间的,在加号,选择第二个。
第五步:按照下图所示分别弄成WSAD。
第一种.添加组件
第六步:然后关闭此窗口,选中你的player,添加组件Player Input.然后点击组件中的create,创建到我们原来的文件里(Settings-Input System)。
第七步:在PlayerInput组件中,将Behavior选成Invoke Unity Events。然后下边的各种方法你就可以选择了。
第二种.代码控制
第八步:用代码控制就先将PlayerInput组件删除。然后选中Input System中的PlayerInputControl,如图所示操作。
点击apply 系统会自动生成脚本。
第九步:在Player中创建一个代码PlayerController,双击打开。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public PlayerInputControl inputControl;
private Rigidbody2D rb;
public Vector2 inputDirection;
public float speed;
private void Awake()
{
inputControl = new PlayerInputControl();
rb = GetComponent<Rigidbody2D>();
}
private void OnEnable()
{
inputControl.Enable();
}
private void OnDisable()
{
inputControl.Disable();
}
private void Update()
{
inputDirection = inputControl.Gameplay.Move.ReadValue<Vector2>();
}
//产生移动通常在FixedUpdate中调用
private void FixedUpdate()
{
Move();
}
public void Move()
{
rb.velocity = new Vector2(inputDirection.x * speed * Time.deltaTime, rb.velocity.y);
}
}
有关参数: