【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判断语句使人物进行移动
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库