搜索

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


发布时间: 2022-11-24 18:24:05    浏览次数:111 次

第一种方法:使用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判断语句使人物进行移动

免责声明 【Unity】2D基础教程(1)——控制角色移动的几种方法,资源类别:文本, 浏览次数:111 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 06:24:05。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/C418-minecraft/p/16814469.html