C418

【Unity】2D基础教程(1)——控制角色移动的几种方法

第一种方法:使用Input.GetAxisRaw()方法

Input.GetAxisRaw是在UnityEngine里的内置方法,其用法为

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        float speed = Input.GetAxisRaw("Horizontal") * Time.deltaTime;
        transform.Rotate(0, speed, 0);
    }
}

如上代码中的speed,这个变量会获取到Input.GetAxisRaw的值(1||0||-1),我们可以用speed这个变量作为控制角色动画的判断条件

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public Animator anim;//使用动画组件
    void Update()
    {
        float speed = Input.GetAxisRaw("Horizontal") * Time.deltaTime;
        transform.Rotate(0, speed, 0);
    }
    
    void SwitchAni()
    {
        if(speed == 1)
        {
            anim.SetBool("move",true);//move需要在unity编辑器中设置一个名为move的Parameters,设置好状态机
        }
    }
}

那么当我们按右方向键的时候,speed的值变为1,那么播放人物朝向右行走的动画,简单的人物移动就完成啦

第二种方法:使用Input.GetKey()方法

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public float speed;
    void Update()
    {
        if (Input.GetKey(KeyCode.A))

            {

                transform.position += new Vector3(0.1f, 0, 0);

            }

            else  if (Input.GetKey(KeyCode.D))

            {

                transform.position += new Vector3(-0.1f, 0, 0);

            }

            else if (Input.GetKey(KeyCode.W))

            {

                transform.position += new Vector3(0, 0, 0.1f);

            }

            else if (Input.GetKey(KeyCode.S))

            {

                transform.position += new Vector3(0, 0, -0.1f);

            }
    }
}

 键盘监听,输入对应的键盘上的值便使其Input.GetKey()的值变为1,通过if判断语句使人物进行移动

posted @   C41829  阅读(1171)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示