【宝贝项目001】【开发日志003】【Unity】长按和射线Debug
长按功能
先在Input的Actions中的Interactions添加Hold。
在代码中,使用 WasPerformedThisFrame() 读取。
WasPressedThisFrame()是刚按下按键的第一帧就立刻触发了,此时 New Input System 的 Hold(长按)计时器才刚刚开始,所以它不会等待长按过程完成。
Action 的三个生命周期
配置了 Hold Interaction 后,这个按键的生命周期分为三个阶段:
| 阶段 | 触发时机 | 对应 API |
|---|---|---|
Started |
刚按下按键(开始计时) | WasPressedThisFrame() |
Performed |
长按达到了设定时间(长按成功) | WasPerformedThisFrame() |
Canceled |
时间还没到就松开了按键(长按中断) | WasReleasedThisFrame() |
拓展:如果想要“蓄力 UI 进度条”效果
如果你希望玩家按住 E 键时,屏幕上有个圆圈在慢慢填满(蓄力提示),可以通过以下方式获取长按进度:
// 1. 是否正处于按住蓄力状态
bool isHolding = inputActions.Player.Interact.IsPressed();
// 2. 获取当前按键所在的 phase
var currentPhase = inputActions.Player.Interact.phase;
bool isCharging = currentPhase == UnityEngine.InputSystem.InputActionPhase.Started;
// 3. 如果在 Update 里给蓄力条加进度:
if (isCharging)
{
// 播放 UI 蓄力动画或填充进度条
}
射线Debug
Physics.Raycast 本身不会自动渲染图形,但 Unity 提供了专门用于调试射线的 Debug.DrawRay 和 Debug.DrawLine。
你可以把它们和 Physics.Raycast 写在一起,在运行(Play 模式)时可视化射线的方向和检测距离。
写法示例
在代码里将射线检测与画线结合,并根据是否击中目标显示不同颜色:
Vector3 origin = transform.position;
Vector3 direction = transform.forward;
float distance = 0.8f;
// 1. 执行物理射线检测
bool isHit = Physics.Raycast(origin, direction, out RaycastHit hit, distance, obstacleLayer);
// 2. 绘制调试射线
// 击中画红线,没击中画绿线,持续时间设为 0.5 秒(方便眼看清)
Color rayColor = isHit ? Color.red : Color.green;
Debug.DrawRay(origin, direction * distance, rayColor, 0.5f);
if (isHit)
{
Debug.Log($"击中了目标物体: {hit.collider.name}");
}
注意事项与使用技巧
-
Debug.DrawRay与Debug.DrawLine的区别:Debug.DrawRay(起点, 方向 * 长度):第二个参数必须乘上距离,否则长度默认只有 1 米。Debug.DrawLine(起点, 终点):传入两个绝对坐标点(比如起点到hit.point)。
-
如何在 Game 画面中看到射线:
- 默认情况下,调试射线只会在 Scene 窗口中显示。
- 如果想在 Game 窗口里也看到射线,只需在 Game 视图右上方勾选
Gizmos按钮。
-
duration参数(持续时间):- 不填(或设为
0):射线只存在 1 帧,适合写在Update()里的频繁检测。 - 填入数值(如
0.5f):射线会在场景中留存 0.5 秒后消失。
- 不填(或设为
拓展:盒子Debug
BoxCast:
bool isHit = Physics.BoxCast(
center, // 起点
halfExtents, // 半尺寸
direction, // 方向
out hit,
transform.rotation,
castDistance,
obstacleLayer
);
BoxCast 无法直接用 Debug.DrawRay 绘制,推荐在脚本里加上 OnDrawGizmosSelected ,这样在 Scene 窗口里选中玩家时就能实时看到这个透明盒子的检测范围:
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Vector3 center = transform.position + Vector3.up * (boxSize.y * 0.5f);
Vector3 direction = transform.forward;
// 绘制起始盒
Gizmos.matrix = Matrix4x4.TRS(center, transform.rotation, Vector3.one);
Gizmos.DrawWireCube(Vector3.zero, boxSize);
// 绘制终点盒
Gizmos.color = Color.red;
Gizmos.matrix = Matrix4x4.TRS(center + direction * castDistance, transform.rotation, Vector3.one);
Gizmos.DrawWireCube(Vector3.zero, boxSize);
}
注意:OnDrawGizmosSelected() 只能写在继承了 MonoBehaviour 的类里才会生效。

浙公网安备 33010602011771号