首页 > 其他分享 >【Unity】2D基础教程(1)——控制角色移动的几种方法

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

时间:2022-10-21 18:45:19浏览次数:45  
标签:transform GetKey 2D Unity 基础教程 using Input speed public

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

标签:transform,GetKey,2D,Unity,基础教程,using,Input,speed,public
From: https://www.cnblogs.com/C418-minecraft/p/16814469.html

相关文章