diff --git a/Assets/Tests/InputSystem/CoreTests_Devices.cs b/Assets/Tests/InputSystem/CoreTests_Devices.cs index ed90efe605..6441084cdc 100644 --- a/Assets/Tests/InputSystem/CoreTests_Devices.cs +++ b/Assets/Tests/InputSystem/CoreTests_Devices.cs @@ -2669,6 +2669,115 @@ public void Devices_CanCheckAnyKeyOnKeyboard() Assert.That(keyboard.anyKey.isPressed, Is.True); } + // UUM-144317: anyKey stays pressed while any key is held, so a key going down while another one was held + // did not register as a press. + [Test] + [Category("Devices")] + public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_WhenKeyGoesDownWhileAnotherIsHeld() + { + var keyboard = InputSystem.AddDevice(); + + // Start tracking frame presses. + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + + Press(keyboard.leftShiftKey); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True); + + InputSystem.Update(); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + + Press(keyboard.aKey); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True); + Assert.That(keyboard.anyKey.wasReleasedThisFrame, Is.False); + + // Releasing one of the held keys is neither a press nor a release. + Release(keyboard.aKey); + Assert.That(keyboard.anyKey.isPressed, Is.True); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + Assert.That(keyboard.anyKey.wasReleasedThisFrame, Is.False); + + Release(keyboard.leftShiftKey); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + Assert.That(keyboard.anyKey.wasReleasedThisFrame, Is.True); + } + + // Same as above, but with full state events like the ones the platform backends send. + [Test] + [Category("Devices")] + public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_WhenKeyGoesDownWhileAnotherIsHeld_WithFullStateEvents() + { + var keyboard = InputSystem.AddDevice(); + + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + + InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift)); + InputSystem.Update(); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True); + + InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift)); + InputSystem.Update(); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + + InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift, Key.A)); + InputSystem.Update(); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True); + } + + // The first query, which starts tracking frame presses, can come in the frame the key goes down. + [Test] + [Category("Devices")] + public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_WhenFirstQueriedAsKeyGoesDownWhileAnotherIsHeld() + { + var keyboard = InputSystem.AddDevice(); + + Press(keyboard.leftShiftKey); + Press(keyboard.aKey); + + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True); + + InputSystem.Update(); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + } + +#if UNITY_EDITOR + // Changing settings refreshes press tracking for both editor and player state, whichever of the two is current. + // That must not mix them up. + [Test] + [Category("Devices")] + public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_KeepsEditorAndPlayerStateApart_WhenSettingsChange() + { + runtime.runInBackground = true; + InputSystem.settings.backgroundBehavior = InputSettings.BackgroundBehavior.IgnoreFocus; + InputSystem.settings.editorInputBehaviorInPlayMode = default; + + var keyboard = InputSystem.AddDevice(); + + // Player state: Shift is held. + InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift)); + InputSystem.Update(InputUpdateType.Dynamic); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True); + + // Without game view focus, keyboard input goes to the editor. Editor state: Shift and A are held. + ScheduleFocusChangedEvent(applicationHasFocus: false); + InputSystem.Update(InputUpdateType.Dynamic); + InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift, Key.A)); + InputSystem.Update(InputUpdateType.Editor); + Assert.That(keyboard.aKey.isPressed, Is.True); + + // Change a setting while player state is current. + InputSystem.Update(InputUpdateType.Dynamic); + InputSystem.settings.defaultDeadzoneMin = 0.2f; + + // Releasing Shift in the editor must not make A, which is still held, look newly pressed. + InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.A)); + InputSystem.Update(InputUpdateType.Editor); + Assert.That(keyboard.aKey.isPressed, Is.True); + Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False); + } + +#endif + [Test] [Category("Devices")] public void Devices_AnyKeyOnKeyboard_DoesNotReactToIMESelected() diff --git a/Assets/Tests/InputSystem/Plugins/WebGLTests.cs b/Assets/Tests/InputSystem/Plugins/WebGLTests.cs index fc3a024a80..3af1c88ea3 100644 --- a/Assets/Tests/InputSystem/Plugins/WebGLTests.cs +++ b/Assets/Tests/InputSystem/Plugins/WebGLTests.cs @@ -116,6 +116,44 @@ public void Devices_SupportsWebGLJoysticks() AssertButtonPress(joystick, new TestJoystickState()); } + // The Trigger control of WebGL joysticks covers the float values of all buttons. A value change of a held + // button can set bits in that state, which must not count as another press. + [Test] + [Category("Devices")] + public void Devices_WebGLJoystickTrigger_WasPressedThisFrame_IsFalse_WhenValueOfHeldButtonChanges() + { + runtime.ReportNewInputDevice(new InputDeviceDescription + { + interfaceName = "WebGL", + deviceClass = "Gamepad", + product = "WebGL test joystick", + capabilities = new WebGLDeviceCapabilities + { + mapping = "", + numAxes = 3, + numButtons = 3 + }.ToJson() + }); + + InputSystem.Update(); + + var joystick = InputSystem.GetDevice(); + var trigger = (ButtonControl)joystick.TryGetChildControl("Trigger"); + + // Start tracking frame presses. + Assert.That(trigger.wasPressedThisFrame, Is.False); + + InputSystem.QueueStateEvent(joystick, new TestJoystickState {button1 = 1.0f}); + InputSystem.Update(); + Assert.That(trigger.wasPressedThisFrame, Is.True); + + // 0.75 has a bit set that 1.0 doesn't have. + InputSystem.QueueStateEvent(joystick, new TestJoystickState {button1 = 0.75f}); + InputSystem.Update(); + Assert.That(trigger.isPressed, Is.True); + Assert.That(trigger.wasPressedThisFrame, Is.False); + } + [Test] [Category("Devices")] public void Devices_CanHaveWebGLJoystickWithBadRegexInName() diff --git a/Packages/com.unity.inputsystem/CHANGELOG.md b/Packages/com.unity.inputsystem/CHANGELOG.md index bf52fc0bd5..921067d5f4 100644 --- a/Packages/com.unity.inputsystem/CHANGELOG.md +++ b/Packages/com.unity.inputsystem/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Fixed touch input from Unity Remote 5 being ignored in Unity 6000.5 and newer. [UUM-155327](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-155327) - Fixed actions enabled during startup, for example in an Entities system's `OnCreate`, being disabled when entering Play Mode with domain reload disabled and in Player builds. [UUM-151403](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-151403) - Fixed the Player Input component Inspector not showing the action map events after the Behavior is set to Invoke Unity Events, until the GameObject was selected again. [UUM-150956](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-150956) +- Fixed `Keyboard.anyKey.wasPressedThisFrame` not returning true when a key is pressed while another key is held. This means it can now be true several times without `wasReleasedThisFrame` in between. [UUM-144317](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-144317) - Fixed a control declared for several variants at once (for example `"variants" : "A;B"`) only merging with derived layouts under its first variant; derived overrides for the other variants lost the base control's layout, offset, format and usages. [UUM-160829](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-160829) ## [1.20.1] - 2026-10-05 diff --git a/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/AnyKeyControl.cs b/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/AnyKeyControl.cs index 8a9ce34c13..1145358d8e 100644 --- a/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/AnyKeyControl.cs +++ b/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/AnyKeyControl.cs @@ -1,5 +1,7 @@ +using Unity.Collections.LowLevel.Unsafe; using UnityEngine.InputSystem.Layouts; using UnityEngine.InputSystem.LowLevel; +using UnityEngine.InputSystem.Utilities; ////REVIEW: generalize this to AnyButton and add to more devices? @@ -13,12 +15,22 @@ namespace UnityEngine.InputSystem.Controls /// /// This control is used by to create a button /// that is toggled on as long as any of the keys on the keyboard is pressed. + /// + /// For , is true in any + /// frame in which a key goes down, even if other keys are already held. + /// is only true in the frame in which the last held key + /// is released. This means that there can be several presses in a row without a release in between. /// /// [InputControlLayout(hideInUI = true)] public class AnyKeyControl : ButtonControl { - ////TODO: wasPressedThisFrame and wasReleasedThisFrame + // The state as of the last press state update, to find keys that went down since. The editor has its own + // state buffers, so it gets its own copy. + private byte[] m_LastState; +#if UNITY_EDITOR + private byte[] m_LastStateEditor; +#endif /// /// Default initialization. Sets state size to 1 bit and format to @@ -35,5 +47,65 @@ public override unsafe float ReadUnprocessedValueFromState(void* statePtr) { return this.CheckStateIsAtDefault(statePtr) ? 0.0f : 1.0f; } + + internal override unsafe bool CheckForRepress(bool editorState, bool startTracking) + { + // Only on keyboards is each bit of the state a key, so that a bit going from 0 to 1 is a key going down. + // Other devices use this control over other kinds of state, such as the float button values of WebGL + // joysticks, where a value change can also set bits. Check the device rather than set a flag in + // Keyboard.FinishSetup, because the precompiled FastKeyboard doesn't call it. + if (!(device is Keyboard)) + return false; + +#if UNITY_EDITOR + ref var lastState = ref editorState ? ref m_LastStateEditor : ref m_LastState; +#else + ref var lastState = ref m_LastState; +#endif + + // Press tracking for editor and player state can be updated while the other one is current (for example + // after a settings change), so read the state buffers of the requested one rather than the current ones. + var updateType = editorState ? InputUpdateType.Editor : InputUpdateType.Dynamic; + var statePtr = (byte*)GetStatePtr(updateType, previousFrame: false); + if (statePtr == null) + return false; + statePtr += m_StateBlock.byteOffset; + + var sizeInBytes = (int)((m_StateBlock.bitOffset + m_StateBlock.sizeInBits + 7) >> 3); + var isNewSnapshot = lastState == null || lastState.Length != sizeInBytes; + if (isNewSnapshot) + lastState = new byte[sizeInBytes]; + + var keyWentDown = false; + fixed(byte* lastStatePtr = lastState) + { + // Compare against the previous frame when tracking starts, so that a key that went down in this + // frame still counts. + if (startTracking) + { + var previousStatePtr = (byte*)GetStatePtr(updateType, previousFrame: true) + m_StateBlock.byteOffset; + UnsafeUtility.MemCpy(lastStatePtr, previousStatePtr, sizeInBytes); + } + else if (isNewSnapshot) + { + UnsafeUtility.MemCpy(lastStatePtr, statePtr, sizeInBytes); + return false; + } + + var endBit = m_StateBlock.bitOffset + m_StateBlock.sizeInBits; + for (var bit = m_StateBlock.bitOffset; bit < endBit; ++bit) + { + if (MemoryHelpers.ReadSingleBit(statePtr, bit) && !MemoryHelpers.ReadSingleBit(lastStatePtr, bit)) + { + keyWentDown = true; + break; + } + } + + UnsafeUtility.MemCpy(lastStatePtr, statePtr, sizeInBytes); + } + + return keyWentDown; + } } } diff --git a/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs b/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs index bb5ad0f9bc..84fefc16c2 100644 --- a/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs +++ b/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs @@ -215,7 +215,8 @@ public bool isPressed // When we start caring about inter-frame presses, use the info we have to set up the alternate path. // If we don't do this, users could call wasPressedThisFrame/wasReleasedThisFrame twice for the first time in // a single frame, and the returned value may be incorrect until the next frame. - private void BeginTestingForFramePresses(bool currentlyPressed, bool pressedLastFrame) + // Returns whether the button was pressed in the last update of the device. + private bool BeginTestingForFramePresses(bool currentlyPressed, bool pressedLastFrame) { needsToCheckFramePress = true; device.m_ButtonControlsCheckingPressState.Add(this); @@ -223,20 +224,26 @@ private void BeginTestingForFramePresses(bool currentlyPressed, bool pressedLast #if UNITY_EDITOR if (InputUpdate.s_LatestUpdateType.IsEditorUpdate()) { + var wasPressedAgain = CheckForRepress(true, startTracking: true); + var wasPressed = currentlyPressed && (!pressedLastFrame || wasPressedAgain); m_LastUpdateWasPressEditor = currentlyPressed; - if (currentlyPressed && !pressedLastFrame) + if (wasPressed) m_UpdateCountLastPressedEditor = device.m_CurrentUpdateStepCount; else if (pressedLastFrame && !currentlyPressed) m_UpdateCountLastReleasedEditor = device.m_CurrentUpdateStepCount; + return wasPressed; } else #endif { + var wasPressedAgain = CheckForRepress(false, startTracking: true); + var wasPressed = currentlyPressed && (!pressedLastFrame || wasPressedAgain); m_LastUpdateWasPress = currentlyPressed; - if (currentlyPressed && !pressedLastFrame) + if (wasPressed) m_UpdateCountLastPressed = device.m_CurrentUpdateStepCount; else if (pressedLastFrame && !currentlyPressed) m_UpdateCountLastReleased = device.m_CurrentUpdateStepCount; + return wasPressed; } } @@ -288,9 +295,9 @@ public bool wasPressedThisFrame { var currentlyPressed = IsValueConsideredPressed(value); var pressedLastFrame = IsValueConsideredPressed(ReadValueFromPreviousFrame()); - BeginTestingForFramePresses(currentlyPressed, pressedLastFrame); + var wasPressed = BeginTestingForFramePresses(currentlyPressed, pressedLastFrame); - return device.wasUpdatedThisFrame && currentlyPressed && !pressedLastFrame; + return device.wasUpdatedThisFrame && wasPressed; } #if UNITY_EDITOR @@ -349,6 +356,7 @@ public bool wasReleasedThisFrame internal void UpdateWasPressed() { var isNowPressed = IsValueConsideredPressed(value); + var wasPressedAgain = CheckForRepress(false, startTracking: false); if (m_LastUpdateWasPress != isNowPressed) { @@ -359,12 +367,26 @@ internal void UpdateWasPressed() m_LastUpdateWasPress = isNowPressed; } + else if (isNowPressed && wasPressedAgain) + { + m_UpdateCountLastPressed = device.m_CurrentUpdateStepCount; + } + } + + // Lets a button that is made up of several inputs, such as AnyKeyControl, report a new press while it is + // already held, when another of its inputs goes down. Called on every press state update, and once when + // press tracking starts, in which case it compares against the previous frame. Returns true if there was + // such a press since the previous call. + internal virtual bool CheckForRepress(bool editorState, bool startTracking) + { + return false; } #if UNITY_EDITOR internal void UpdateWasPressedEditor() { var isNowPressed = IsValueConsideredPressed(value); + var wasPressedAgain = CheckForRepress(true, startTracking: false); if (m_LastUpdateWasPressEditor != isNowPressed) { @@ -375,6 +397,10 @@ internal void UpdateWasPressedEditor() m_LastUpdateWasPressEditor = isNowPressed; } + else if (isNowPressed && wasPressedAgain) + { + m_UpdateCountLastPressedEditor = device.m_CurrentUpdateStepCount; + } } #endif // UNITY_EDITOR diff --git a/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/InputControl.cs b/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/InputControl.cs index 9cdc7734f8..f7d2d845ac 100644 --- a/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/InputControl.cs +++ b/Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/InputControl.cs @@ -923,6 +923,18 @@ protected virtual void RefreshConfiguration() /// protected internal unsafe void* previousFrameStatePtr => InputStateBuffers.GetBackBufferForDevice(GetDeviceIndex()); + // Like currentStatePtr and previousFrameStatePtr, but reads the state buffers of the given update type + // instead of the ones of the current update. + internal unsafe void* GetStatePtr(InputUpdateType updateType, bool previousFrame) + { + var buffers = InputSystem.manager.m_StateBuffers.GetDoubleBuffersFor(updateType); + if (!buffers.valid) + return null; + + var deviceIndex = GetDeviceIndex(); + return previousFrame ? buffers.GetBackBuffer(deviceIndex) : buffers.GetFrontBuffer(deviceIndex); + } + /// /// The default state data buffer ///