unity3d如何通过input类捕获鼠标移动并同步到相机视角转动上,以及wsad键移动,就像第一人称游戏一样
时间: 2025-02-10 07:15:30 浏览: 99
在Unity中,要实现类似的第一人称游戏的交互,你需要监听Input类中的鼠标输入事件,并结合键盘的WASD键来控制相机和角色移动。下面是一个简单的步骤和代码示例:
首先,在Unity编辑器中,创建一个新的C#脚本,命名为`FirstPersonControls`,然后将以下内容粘贴到脚本中:
```csharp
using UnityEngine;
using UnityEngine.InputSystem;
public class FirstPersonControls : MonoBehaviour
{
public Transform playerBody; // 设置玩家角色的变换对象
public Camera mainCamera; // 设置主相机
private Vector2 mouseLook; // 存储鼠标视角信息
private float moveSpeed = 5f; // 移动速度
private float cameraSensitivity = 45f; // 鼠标灵敏度
private PlayerInput inputManager; // 输入管理器实例
private void Awake()
{
inputManager = new PlayerInput(); // 初始化输入管理器
inputManager.AddActionMapping("Move", new AxisMapper { axis = "Horizontal", deadZone = 0.1f });
inputManager.AddActionMapping("Look", new AxisMapper { axis = "Vertical", deadZone = 0.1f });
// 注册事件处理
inputManager.Move.performed += OnMove;
inputManager.Look.performed += OnLook;
}
private void Update()
{
if (inputManager.IsConnected())
{
// 捕获鼠标移动
mouseLook = inputManager.GetAction("Look").value.ReadValue<Vector2>().normalized;
// 根据鼠标和键盘输入调整相机视角
transform.RotateAround(playerBody.position, Vector3.up, mouseLook.x * Time.deltaTime * cameraSensitivity);
// WASD键移动
var movement = inputManager.GetAxis("Move");
playerBody.Translate(movement * moveSpeed * Time.deltaTime, Space.World);
}
}
private void OnMove(InputAction.CallbackContext context)
{
// 当"Move"动作被触发时,执行回调
Debug.Log($"Player moved left: {context.ReadValue<float>() < 0}");
}
private void OnLook(InputAction.CallbackContext context)
{
// 当"Look"动作被触发时,执行回调
Debug.Log($"Player looked up: {context.ReadValue<float>() > 0}");
}
}
```
在这个脚本中,我们首先初始化了一个`PlayerInput`实例,用于接收用户输入。然后,我们注册了两个轴映射事件:`Move`负责水平方向的移动,`Look`负责垂直视角变化。在`Update`函数里,我们实时获取用户的输入,并相应地调整相机和角色的位置。
记得在场景中设置好玩家角色的`playerBody`变量,并将此脚本应用到包含相机的GameObject上。
阅读全文
相关推荐
















