上一篇文章介绍了如何在Unity中接收用户的输入,由于需要兼容各个设备的差异,Unity做了一套封装,初用起来可能会比较绕,本篇我们就直接用起来,我们会利用wasd来移动我们的游戏内的视线,有点类似FPS游戏里面的操作效果,同时我们也会学习如何让我们的代码控制场景内的物体,而非只是控制组件自己所在的物体。
组件接收WASD输入
我们新建一个代码资源文件叫CameraController:
using UnityEngine;
public class CameraController : MonoBehaviour
{
void Update()
{
if (Input.GetKey(KeyCode.W))
{
// Move camera forward
}
if (Input.GetKey(KeyCode.A))
{
// Move camera left
}
if (Input.GetKey(KeyCode.S))
{
// Move camera backward
}
if (Input.GetKey(KeyCode.D))
{
// Move camera right
}
}
}
可以看到我们用上一篇讲的Input类来获取当前用户按下了什么按键,但是我们也说了,如果我们不是用的键盘,如果是手柄呢?那么我们最好还是使用Axis信息来代表类似移动输入的信息,我们让GPT简单帮我改改代码:
using UnityEngine;
public class CameraController : MonoBehaviour
{
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
}
}
"Horizontal"和"Vertical"都是可以从InputManager配置文件里面找到对应的配置名的,很明显这两个分别代表水平和竖直方向上的输入量,float取值范围是[-1, 1]。
但是细心的人真的会看到InputManager里面针对这两个输入并没有配置具体是键盘上的哪个按键,怎么就一定会是WASD呢,那只能说是Unity的潜规则,可以从文档中了解到:
To read an axis use Input.GetAxiswith one of the following default axes: "Horizontal" and "Vertical" are mapped to joystick,A,W,S,Dand the arrow keys. "Mouse X" and "Mouse Y" are mapped to the mouse delta. "Fire1", "Fire2" "Fire3" are mapped toCtrl,Alt,Cmdkeys and three mouse or joystick buttons.
给相机加上我们的组件
现在我们是希望移动相机的位置,那么很显然我们需要修改相机的Transform组件的Position信息,我们先给相机加上我们自己的组件:
然后在我们的组件里面要访问同一个GameObject下的其他组件,那么我们可以直接使用GetComponent方法:
using UnityEngine;
public class CameraController : MonoBehaviour
{
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Transform transform = GetComponent<Transform>();
}
}
然后修改组件里面的值:
using U