Unity 按键捕捉技巧分享✨🎮 #开发干货 #编程技巧

john
john 在知识的海洋中遨游

0 人点赞了该文章 · 495 浏览

在Unity中,捕捉按键输入是开发交互式游戏的重要部分。可以通过使用Input类来检测键盘和鼠标的输入事件。以下是一些常见的按键捕捉方法和示例代码。

1. 捕捉键盘输入

使用Input.GetKeyInput.GetKeyDown

  • Input.GetKey:当按住某个键时会持续返回true
  • Input.GetKeyDown:在按下某个键的那一帧返回true


using UnityEngine;

public class KeyboardInput : MonoBehaviour
{
void Update()
{
// 检测持续按键
if (Input.GetKey(KeyCode.W))
{
Debug.Log("按住W键");
}

// 检测按键按下
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("按下空格键");
}

// 检测按键抬起
if (Input.GetKeyUp(KeyCode.Space))
{
Debug.Log("抬起空格键");
}
}
}

2. 捕捉鼠标输入

使用Input.GetMouseButtonInput.GetMouseButtonDown

  • Input.GetMouseButton:当按住鼠标按钮时会持续返回true
  • Input.GetMouseButtonDown:在按下鼠标按钮的那一帧返回true

using UnityEngine;

public class MouseInput : MonoBehaviour
{
void Update()
{
// 检测持续按住鼠标左键
if (Input.GetMouseButton(0))
{
Debug.Log("按住鼠标左键");
}

// 检测按下鼠标右键
if (Input.GetMouseButtonDown(1))
{
Debug.Log("按下鼠标右键");
}

// 检测抬起鼠标中键
if (Input.GetMouseButtonUp(2))
{
Debug.Log("抬起鼠标中键");
}
}
}


3. 捕捉轴输入

使用Input.GetAxisInput.GetAxisRaw

Input.GetAxisInput.GetAxisRaw用于捕捉模拟输入轴的变化,例如WASD键、方向键或游戏手柄的摇杆。


using UnityEngine;

public class AxisInput : MonoBehaviour
{
void Update()
{
// 捕捉水平轴输入
float horizontal = Input.GetAxis("Horizontal");
Debug.Log("水平轴输入: " + horizontal);

// 捕捉垂直轴输入
float vertical = Input.GetAxis("Vertical");
Debug.Log("垂直轴输入: " + vertical);
}
}


4. 使用InputManager自定义按键

可以在Unity的Input Manager中定义自定义按键。以下是自定义“Jump”按键的示例:

设置自定义按键

  1. 打开Unity Editor,选择Edit > Project Settings > Input Manager
  2. 展开Axes,找到Jump或创建一个新的输入轴。
  3. 设置名称(例如“Jump”)和正按钮(例如“space”)。

在脚本中使用自定义按键


using UnityEngine;

public class CustomInput : MonoBehaviour
{
void Update()
{
// 检测自定义按键
if (Input.GetButtonDown("Jump"))
{
Debug.Log("按下Jump键");
}
}
}


5. 组合按键检测

可以通过组合多个按键来实现更复杂的输入检测。



using UnityEngine;

public class ComboInput : MonoBehaviour
{
void Update()
{
// 检测同时按下Ctrl和Shift键
if (Input.GetKey(KeyCode.LeftControl) && Input.GetKey(KeyCode.LeftShift))
{
Debug.Log("按住Ctrl和Shift键");
}

// 检测按下Ctrl+C组合键
if (Input.GetKeyDown(KeyCode.C) && Input.GetKey(KeyCode.LeftControl))
{
Debug.Log("按下Ctrl+C组合键");
}
}
}

通过这些方法,可以在Unity中实现各种按键输入的检测,从而使游戏具有更丰富的交互性和操作性。

发布于 2024-05-28 07:16

免责声明:

本文由 john 原创或转载,著作权归作者所有,如有侵权,请联系我们删除。 info@frelink.top

登录一下,更多精彩内容等你发现,贡献精彩回答,参与评论互动

登录! 还没有账号?去注册

暂无评论

All Rights Reserved Frelink ©2025