unity键盘控制移动操作(WASD)篇 |
您所在的位置:网站首页 › unity控制人物移动 › unity键盘控制移动操作(WASD)篇 |
今天仔细重新研究了下移动操作,发现input.key那种方法纯属是讨巧操作,实际上它并不好用,在高性能电脑中,我们的电脑每帧有可能会运行上千帧,如果采用这种方法会发生发卡顿,远远没有以下方案丝滑 方案来自unity官网教学视频改写本篇博客内容,原网址如下: Lesson 2.1 - Player Positioning - Unity Learnhttps://learn.unity.com/tutorial/lesson-2-1-control-player-bounds-with-if-then-statements?uv=2020.3&missionId=5f71fe63edbc2a00200e9de0&pathwayId=5f7e17e1edbc2a5ec21a20af&contentId=5f7229b2edbc2a001f834db7&projectId=5cdcc312edbc2a24a41671e6#首先我们先 1.在场景中建一个模型。 2创建一个脚本,挂载到模型上。 然后再脚本中代码书写如下: //声明部分 public float horizontalinput;//水平参数 public float Verticalinput;//垂直参数 float speed=10.0f;//声明一个参数,没有规定 //在update中书写 void Update() { horizontalinput = Input.GetAxis("Horizontal"); //AD方向控制 Verticalinput = Input.GetAxis("Vertical"); //WS方向控制 this.transform.Translate(Vector3.right * horizontalinput * Time.deltaTime * speed); 控制该物体向侧方移动 this.transform.Translate(Vector3.forward* Verticalinput * Time.deltaTime * speed); //控制该物体向前后移动 }之后保存,你就会发现即使WA、WD、AS、SD一起按也会有移动效果 ------------------------------------------------------- WA、WD、AS、SD一起按也会有移动效果,但是你会发现他们在斜着移动时速度变快了 于是加入以下代码进行限制他们斜着移动的速度 if (horizontalinput!=0&&Verticalinput!=0) { horizontalinput = horizontalinput * 0.6f; Verticalinput = Verticalinput * 0.6f; }最后完善的代码: //声明部分 public float horizontalinput;//水平参数 public float Verticalinput;//垂直参数 float speed=10.0f;//声明一个参数,没有规定 //在update中书写 void Update() { horizontalinput = Input.GetAxis("Horizontal"); //AD方向控制 Verticalinput = Input.GetAxis("Vertical"); if (horizontalinput!=0&&Verticalinput!=0) { horizontalinput = horizontalinput * 0.6f; Verticalinput = Verticalinput * 0.6f; } //WS方向控制 this.transform.Translate(Vector3.right * horizontalinput * Time.deltaTime * speed); 控制该物体向侧方移动 this.transform.Translate(Vector3.forward* Verticalinput * Time.deltaTime * speed); //控制该物体向前后移动 } |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |