Pressed This Frame
Part of the Building Real Games section of Coddy's Unity journey. Lesson 46 of 60.
isPressed answers "is it down now?" on every frame of a hold. For something that should happen once per press, a control has two more answers: wasPressedThisFrame is true only on the frame the key or button went down, and wasReleasedThisFrame only on the frame it came back up. They take the place of Input.GetKeyDown and Input.GetKeyUp, and of GetMouseButtonDown and GetMouseButtonUp. This rubber stamp goes down when the mouse button is pressed and lifts when it is let go:
using UnityEngine;
using UnityEngine.InputSystem;
public class Stamp : MonoBehaviour
{
public float drop = 0.5f;
private int stamps;
void Update()
{
Mouse mouse = Mouse.current;
if (mouse.leftButton.wasPressedThisFrame)
{
transform.position += Vector3.down * drop;
stamps++;
Debug.Log("Stamp " + stamps);
}
if (mouse.leftButton.wasReleasedThisFrame)
{
transform.position += Vector3.up * drop;
}
}
}A click held for half a second logs Stamp 1 once, moves the stamp down once and back up once. With isPressed in the first if, the same click would log about 30 stamps and sink the stamp 15 units into the desk. Keys work the same way: Keyboard.current.spaceKey.wasPressedThisFrame is true once per press of Space.
Challenge
MediumStart the sprinter on Space: down to crouch, up to run.
- In
Update(), when!runningandKeyboard.current.spaceKey.wasPressedThisFrame: setset, move downcrouch, logSet. - When
setandwasReleasedThisFrame: clearset, setrunning, move upcrouch, logGo!. - While
running, move along +z atspeedunits a second.
Press Play, hold Space and let go: Set, then Go! in the Console. Then Check.
Try it yourself
using UnityEngine;
using UnityEngine.InputSystem;
public class Sprinter : MonoBehaviour
{
public float speed = 6f;
public float crouch = 0.3f;
private bool set;
private bool running;
void Update()
{
// Space down: crouch and log Set. Space up: stand, log Go! and run.
}
}
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground