初面网初面网

输入管理

键鼠输入

输入控制大致可以分为三种:键鼠、虚拟轴、手机触摸

键鼠中的输入控制是通过Input类进行管理的

属性方法详解
anyKey任何按键按下都返回true
anyKeyDown任何按键按下第一帧都返回true
InputString该帧的键盘输入
mousePosition鼠标指针当前的坐标位置
GetKey按下按键瞬间返回true
GetKeyDown按下按键瞬间返回一次true
GetKeyUp抬起按键瞬间返回一次true
GetMouseButton按下鼠标键返回true
GetMouseButtonDown按下鼠标键瞬间返回一次true
GetMouseButtonUp抬起鼠标瞬间返回一次true
// 用例
void Update(){
  // 触发一次
  if(Input.GetKeyDown(KeyCode.A)){
    Debug.Log("按下了A键");
  }

  // 持续触发
  if(Input.GetKey(KeyCode.W)){
    Debug.Log("按下了W键");
  }
}

轴输入

需要在Unity引擎中找到"编辑>项目设置>Input Manager",然后将其中的轴进行设置。

虚拟轴名称详解
水平Horizontal水平轴,对应于键盘A/D键,←/→键
垂直Vertical垂直轴,对应于键盘W/S键,↑/↓键
鼠标XMouseX鼠标沿x轴方向移动
鼠标YMouseY鼠标沿y轴方向移动
鼠标滚轮MouseScrollWheel鼠标滚轮滚动
// 用例
void Update(){
  // 轴的正向会返回1,负向会返回-1,未触发轴的时候返回0
  float horizontal = Input.GetAxis("Horizontal");
  Debug.Log(horizontal);
  Debug.Log(Input.GetAxisRaw("Vertical"));  // 边界值。范围-1,0或1

  // 鼠标X轴
  float mouseX = Input.GetAxis("Mouse X");
  Debug.Log(mouseX);

  // 鼠标Y轴
  float mouseY = Input.GetAxis("Mouse Y");
  Debug.Log(mouseY);

  // 鼠标滚轮
  float scroll = Input.GetAxis("Mouse ScrollWheel");
  Debug.Log(scroll);
}
  • 如果虚拟轴只设置了一个按键,则虚拟轴转变为虚拟按键。
虚拟轴名称详解
Fire1Fire1鼠标左键或左Ctrl键
Fire2Fire2鼠标右键或左Alt键
Fire3Fire3鼠标滚轮或左Shift键
跳跃JumpSpace键
提交SubmitReturn键
取消CancelEscape键
  • 手机触摸

手机与其他不同点在于可以支持多点触摸。

// 用例
void Start()
{
  // 开启多点触摸
  Input.multiTouchEnabled = true;
}

void Update(){
  // 判断单点触摸
  if(Input.touchCount == 1){
    // 触摸位置
    Debug.Log(Input.touches[0].position);
  }

  // 触摸阶段
  switch(Input.touches[0].phase){
    case TouchPhase.Began:
      Debug.Log("开始触摸");
      break;
    case TouchPhase.Moved:
      Debug.Log("触摸中并且在移动");
      break;
    case TouchPhase.Ended:
      Debug.Log("触摸结束");
      break;
    case TouchPhase.Canceled:
      Debug.Log("触摸取消");
      break;
    case TouchPhase.Stationary:
      Debug.Log("触摸但未移动");
      break;
  }
}

// 判断多点触摸,如两点触摸
if(Input.touchCount == 2){
  // 两个点触摸位置
  Debug.Log(Input.touches[0].position);
  Debug.Log(Input.touches[1].position);
}

更新于 2026/2/26