统一使用新输入系统

This commit is contained in:
2026-09-20 17:09:58 +08:00
parent 38303b3743
commit 02265e75ca
14 changed files with 644 additions and 117 deletions
+32 -13
View File
@@ -6,12 +6,18 @@ namespace Agame
/// <summary>
/// 第一人称视角控制:鼠标横移带动 body 偏航,纵移带动相机俯仰。
///
/// 输入来自父节点(Player 根)上 PlayerInput 的 Look 动作。
///
/// 网络侧前提(重要):本组件挂在 PlayerCamera 上,而 PlayerCamera 只会被
/// <see cref="PlayerController"/> 为「本地拥有者」启用(见其 ApplyOwnership)。
/// 非拥有者客户端的相机是 disabled 的,因此这里不会执行,天然不需要再判所有权。
///
/// 反过来说:如果日后把 PlayerCamera 改成常驻启用,必须补上所有权判断,
/// 否则每个客户端都会用自己的鼠标去转动别人玩家的视角。
///
/// 关于光标:锁定/释放光标属于「窗口」层面,不是 gameplay 输入,
/// 所以刻意没有做成 Action —— 那样的话玩家一旦切到别的输入上下文
/// (比如打开菜单、禁用了 Player 这张 Map),连恢复光标的按键都收不到了。
/// </summary>
public class MouseLook : MonoBehaviour
{
@@ -27,11 +33,17 @@ namespace Agame
[Tooltip("被偏航(Horizontal)的躯体 Transform,通常是玩家根节点。")]
[SerializeField] private Transform characterBody;
private InputAction _lookAction;
private float _xRotation;
private bool _warnedMissingBody;
private void OnEnable()
{
// PlayerInput 挂在父节点(Player 根)上;相机自身可能是 disabled 的,
// 所以要 includeInactive 才能取到。
PlayerInput playerInput = GetComponentInParent<PlayerInput>(includeInactive: true);
_lookAction = PlayerInputNames.Resolve(playerInput, PlayerInputNames.Look, this);
// 跟随本对象的启用状态锁定光标:只有本地拥有者的相机会被启用,
// 所以光标锁定/释放自然就只在拥有者这一侧发生。
LockCursor(true);
@@ -45,23 +57,16 @@ namespace Agame
private void Update()
{
Mouse mouse = Mouse.current;
if (mouse == null)
return;
// Esc 释放光标,左键重新抓取(方便编辑器里切出去)。
Keyboard kb = Keyboard.current;
if (kb != null && kb.escapeKey.wasPressedThisFrame)
LockCursor(false);
if (mouse.leftButton.wasPressedThisFrame && Cursor.lockState != CursorLockMode.Locked)
LockCursor(true);
UpdateCursorLock();
if (Cursor.lockState != CursorLockMode.Locked)
return;
// 新输入系统下 delta 的单位是像素,不是轴值。
Vector2 delta = mouse.delta.ReadValue();
if (_lookAction == null)
return;
// Look 绑定的是 <Mouse>/delta,读出来的就是这一帧的鼠标位移(单位:像素)。
Vector2 delta = _lookAction.ReadValue<Vector2>();
// 横移:转动躯体
if (characterBody != null)
@@ -81,6 +86,20 @@ namespace Agame
transform.localRotation = Quaternion.Euler(_xRotation, 0f, 0f);
}
/// <summary>
/// Esc 释放光标,左键重新抓取(方便编辑器里切出去)。
/// </summary>
private void UpdateCursorLock()
{
Keyboard keyboard = Keyboard.current;
if (keyboard != null && keyboard.escapeKey.wasPressedThisFrame)
LockCursor(false);
Mouse mouse = Mouse.current;
if (mouse != null && mouse.leftButton.wasPressedThisFrame && Cursor.lockState != CursorLockMode.Locked)
LockCursor(true);
}
private void LockCursor(bool locked)
{
Cursor.lockState = locked ? CursorLockMode.Locked : CursorLockMode.None;
+56 -35
View File
@@ -7,18 +7,20 @@ using UnityEngine.InputSystem;
namespace Agame
{
/// <summary>
/// 玩家移动控制 —— FishNet 客户端授权模式。
/// 参考:Docs/联机方案选型.md §3.3,以及官方教程 "Moving Your Player Around"。
/// 玩家移动控制 —— FishNet 客户端授权 + Input System 的 PlayerInput / Actions 方案。
///
/// 职责边界:本组件只负责「读输入 + 驱动 CharacterController」。
/// 位置/旋转的同步交给 Player 预制体上的 NetworkTransform(Client Authoritative),
/// 这里不写任何 RPC / SyncVar。
/// 输入链路:
/// Assets/_Game/Input/PlayerControls.inputactions
/// → Player 根节点上的 PlayerInput 组件(仅本地拥有者启用)
/// → 本脚本在 Update 里读取 Move / Sprint / Jump
///
/// FishNet 4.7.3 下的三条硬约束:
/// 1. 必须继承 NetworkBehaviour 而非 MonoBehaviour,否则拿不到 IsOwner 与网络生命周期回调。
/// 2. IsOwner 禁止在 Awake / Start / OnStartServer / OnStartNetwork 里访问 ——
/// FishNet 代码生成器会直接抛编译错误,按拥有者初始化的逻辑要放在 OnStartClient。
/// 3. 只有拥有者能驱动自己的对象,少了这道判断就会去移动别人的玩家。
/// 本脚本同时兼任「输入与相机的所有权开关」,见 ApplyOwnership 的注释。
///
/// FishNet 4.7.3 的三条硬约束(与输入方案无关,继续沿用):
/// 1. 必须继承 NetworkBehaviour,否则拿不到 IsOwner 与网络生命周期回调。
/// 2. IsOwner 禁止在 Awake / Start / OnStartServer / OnStartNetwork 中访问 ——
/// FishNet 的 ILPP 会直接报编译错误。
/// 3. 只有拥有者能驱动自己的对象,少了 IsOwner 判断就会去移动别人的玩家。
/// </summary>
[RequireComponent(typeof(CharacterController))]
public class PlayerController : NetworkBehaviour
@@ -33,16 +35,36 @@ namespace Agame
[SerializeField, Min(0f)] private float jumpHeight = 1.5f;
[Header("Ownership")]
[Tooltip("仅本地拥有者需要启用的对象(玩家相机等)。非拥有者会被自动禁用,避免多相机抢占渲染。")]
[Tooltip("仅本地拥有者需要启用的对象(玩家相机等)。非拥有者会自动禁用,避免多相机抢占渲染。")]
[SerializeField] private GameObject[] ownerOnlyObjects;
private CharacterController _controller;
private PlayerInput _playerInput;
private InputAction _moveAction;
private InputAction _jumpAction;
private InputAction _sprintAction;
private Vector3 _verticalVelocity;
private void Awake()
{
// Awake 中不得访问 IsOwner,这里只做纯本地缓存。
_controller = GetComponent<CharacterController>();
_playerInput = GetComponent<PlayerInput>();
if (_playerInput == null)
{
Debug.LogError(
$"[{nameof(PlayerController)}] {name} 上找不到 PlayerInput 组件,输入将不可用。" +
$"请在玩家预制体上加 PlayerInput,并把 Actions 指向 {PlayerInputNames.AssetFileName}。",
this);
return;
}
_moveAction = PlayerInputNames.Resolve(_playerInput, PlayerInputNames.Move, this);
_jumpAction = PlayerInputNames.Resolve(_playerInput, PlayerInputNames.Jump, this);
_sprintAction = PlayerInputNames.Resolve(_playerInput, PlayerInputNames.Sprint, this);
}
public override void OnStartClient()
@@ -59,47 +81,39 @@ namespace Agame
{
base.OnOwnershipClient(prevOwner);
// 所有权可能中途变更(例如将来的主机迁移),相机等要跟着切换。
// 所有权可能中途变更(例如将来的主机迁移),输入与相机要跟着切换。
ApplyOwnership();
}
private void Update()
{
// 只驱动本地拥有者,否则每个客户端都会去移动别人的玩家。
// 只驱动本地拥有者。
if (!IsOwner)
return;
Keyboard kb = Keyboard.current;
if (kb == null)
return;
Vector2 moveInput = _moveAction != null ? _moveAction.ReadValue<Vector2>() : Vector2.zero;
Vector3 moveDirection = BuildMoveDirection(moveInput);
float speed = kb.leftShiftKey.isPressed ? sprintSpeed : moveSpeed;
Vector3 moveDirection = ReadMoveDirection(kb);
bool isSprinting = _sprintAction != null && _sprintAction.IsPressed();
float speed = isSprinting ? sprintSpeed : moveSpeed;
_controller.Move(moveDirection * (speed * Time.deltaTime));
UpdateJumpAndGravity(kb);
bool jumpPressed = _jumpAction != null && _jumpAction.WasPressedThisFrame();
UpdateJumpAndGravity(jumpPressed);
}
/// <summary>
/// 读取 WASD 并转换为相对于角色自身朝向的方向(body 的偏航由 MouseLook 负责)。
/// 斜向输入做归一化,避免对角线移动比正向更快。
/// 把 Move 的二维输入转换为相对于角色自身朝向的三维方向
/// (body 的偏航由 MouseLook 负责)。斜向输入做归一化,避免对角线移动比正向更快。
/// </summary>
private Vector3 ReadMoveDirection(Keyboard kb)
private Vector3 BuildMoveDirection(Vector2 moveInput)
{
float moveX = 0f;
float moveZ = 0f;
if (kb.aKey.isPressed) moveX -= 1f;
if (kb.dKey.isPressed) moveX += 1f;
if (kb.sKey.isPressed) moveZ -= 1f;
if (kb.wKey.isPressed) moveZ += 1f;
Vector3 direction = transform.right * moveX + transform.forward * moveZ;
Vector3 direction = transform.right * moveInput.x + transform.forward * moveInput.y;
return Vector3.ClampMagnitude(direction, 1f);
}
private void UpdateJumpAndGravity(Keyboard kb)
private void UpdateJumpAndGravity(bool jumpPressed)
{
bool isGrounded = _controller.isGrounded;
@@ -107,7 +121,7 @@ namespace Agame
if (isGrounded && _verticalVelocity.y < 0f)
_verticalVelocity.y = -2f;
if (isGrounded && kb.spaceKey.wasPressedThisFrame)
if (isGrounded && jumpPressed)
{
// 由目标跳跃高度反推初速度:v = sqrt(2 * g * h)
_verticalVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
@@ -118,11 +132,18 @@ namespace Agame
}
/// <summary>
/// 按所有权开关"只属于本地玩家"的对象。最典型的是玩家相机:
/// 若每个客户端的相机都常驻启用,N 个玩家就会互相抢渲染。
/// 按所有权统一开关「只属于本地玩家」的东西:PlayerInput 与玩家相机。
///
/// 集中放在这里的原因:这两样都是「一个客户端只该有一份生效」。
/// 散到各脚本里各自 enable 容易漏,而且会出现顺序问题 ——
/// PlayerCamera 上的 MouseLook 在 OnEnable 里就要读 Look 动作,
/// 所以必须先开 PlayerInput、再启用相机,否则第一帧读不到值。
/// </summary>
private void ApplyOwnership()
{
if (_playerInput != null)
_playerInput.enabled = IsOwner;
if (ownerOnlyObjects == null)
return;
+54
View File
@@ -0,0 +1,54 @@
using FishNet.Object;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Serialization;
namespace Agame
{
/// <summary>
/// 按攻击键在当前位置生成一个方块,生成动作经 ServerRpc 在服务端执行。
///
/// 输入来自 Player 根节点上 PlayerInput 的 Attack 动作 —— 与 <see cref="PlayerController"/>
/// 共用同一个 PlayerInput(因此 PlayerInput 的启用/禁用也统一由 PlayerController 按所有权管理,
/// 这里只读动作,不再自己 enable 组件)。
/// </summary>
public class PlayerCubeCreator : NetworkBehaviour
{
[Tooltip("要生成的方块预制体。必须已登记进 FishNet 的可生成预制体列表(DefaultPrefabObjects)。")]
[FormerlySerializedAs("CubePrefab")]
[SerializeField] private NetworkObject cubePrefab;
private InputAction _attackAction;
private void Awake()
{
// Awake 中不得访问 IsOwner,这里只做纯本地缓存。
_attackAction = PlayerInputNames.Resolve(GetComponent<PlayerInput>(), PlayerInputNames.Attack, this);
}
private void Update()
{
// 只让拥有者发起攻击,否则每个客户端都会去指挥别人的玩家造方块。
if (!IsOwner)
return;
if (_attackAction != null && _attackAction.WasPressedThisFrame())
SpawnCube();
}
[ServerRpc]
private void SpawnCube()
{
if (cubePrefab == null)
{
Debug.LogError(
$"[{nameof(PlayerCubeCreator)}] {name} 的 Cube Prefab 没有指定,无法生成方块。",
this);
return;
}
NetworkObject obj = Instantiate(cubePrefab, transform.position, Quaternion.identity);
Spawn(obj); // NetworkBehaviour 对 ServerManager.Spawn 的快捷封装
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 42ed262caf19a9040bf314a318cfecb6
+70
View File
@@ -0,0 +1,70 @@
using UnityEngine;
using UnityEngine.InputSystem;
namespace Agame
{
/// <summary>
/// 输入资产 Assets/_Game/Input/PlayerControls.inputactions 的名称与取值入口。
///
/// 把 Action 名集中在这里,是为了避免 "Move"/"Look"/"Attack" 这类字符串散落在三个脚本里 ——
/// 将来在输入资产里改名,只需要动这一处。
///
/// 约定:三个玩家脚本一律从 PlayerInput 实例上取 Action,而不是各自序列化一个资产引用。
/// 因为 PlayerInput 可能为每个玩家实例化一份 Actions 副本,从实例上取才能拿到正确的那一份。
/// </summary>
public static class PlayerInputNames
{
/// <summary>输入资产的文件名,仅用于错误提示。</summary>
public const string AssetFileName = "PlayerControls.inputactions";
/// <summary>Action Map 名称,需与输入资产中的 Map 一致。</summary>
public const string ActionMap = "Player";
public const string Move = "Move";
public const string Look = "Look";
public const string Jump = "Jump";
public const string Sprint = "Sprint";
public const string Attack = "Attack";
/// <summary>
/// 从 PlayerInput 上解析指定 Action,解析失败时返回 null 并给出明确的错误信息。
/// 这里刻意用 LogError 而不是直接抛 NullReferenceException ——
/// "输入没反应但又不报错"是这类问题里最难排查的一种,必须留下痕迹。
/// </summary>
public static InputAction Resolve(PlayerInput playerInput, string actionName, Object context)
{
string ownerName = context != null ? context.name : "(未知对象)";
if (playerInput == null)
{
Debug.LogError(
$"[{nameof(PlayerInputNames)}] {ownerName} 上找不到 PlayerInput 组件,无法读取输入。" +
$"请在玩家预制体上加 PlayerInput 组件,并把 Actions 指向 {AssetFileName}。",
context);
return null;
}
InputActionAsset asset = playerInput.actions;
if (asset == null)
{
Debug.LogError(
$"[{nameof(PlayerInputNames)}] {ownerName} 的 PlayerInput 没有指定 Actions 资产," +
$"请把 {AssetFileName} 拖进 PlayerInput 的 Actions 槽。",
context);
return null;
}
InputAction action = asset.FindAction(actionName, throwIfNotFound: false);
if (action == null)
{
Debug.LogError(
$"[{nameof(PlayerInputNames)}] {AssetFileName} 里找不到名为 \"{actionName}\" 的动作," +
"请确认 Map 与 Action 名和脚本里的一致。",
context);
return null;
}
return action;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 379ed2c2823ca764982411eec577adce