Unity2D学习日志(一)人物移动

Unity version-2022.3

切换Input System Package

1.unity默认为Input Manager,需在Editor ->project setting中切换为Input System Package,切换完成后提示需要重启。

切换Input System Package
2.重启之后在Windows -> Package Manager -> Unity Registry 中安装Input System。
安装InputSystem

3.为主控节点添加Player Input组件,主控节点一般为空结点,尽量不要将主控脚本挂载玩家模型上。
添加组件
4.点击Create Actions,创建默认Action文件,注意文件命名,后续需要在C#脚本中引入,我在代码实例中标记了 ①。
创建Actions文件
5.创建Action文件文件后,在检查器选中Generate C# 类,默认与Action文件同名。
生成C#脚本!
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。

初学小白学习日志,欢迎指点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SoneHow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值