Container.Held? (solved by Container.Pressed)

Is there a way to differentiate between holding a key versus pressing a key. For example, I am trying to make it to where if you press A you turn in a direction, but if you hold it you move in said direction.

Sorry yet again if this is a stupid question :laughing:

You could just have some variable (boolean, for example) to store if desired key was pressed (in Press method) and clear it in Release method (by same key code). And in Update method you just check if the state of key you stored is present and perform your action :slight_smile:
Hope it helps!
Ofc there could be more specific methods in specific cases (like using only update method, or some global keys state handler), but the one I described is most basic one and should work without any confusion of the reader of code (which more sophisticated methods usually lack)

1 Like

I swear sometimes I try to make things way, way harder than it actually is. Tysm.

Note that there is already such variable :), that is: we track the state of which key is pressed for you, so you don’t need to implement Press / Release to track it yourself:

Just check Container.Pressed[keyA]. If you want to do something when user is holding a key, you can just do something like

procedure TViewMain.Update(const SecondsPassed: Single; var HandleInput: Boolean);
begin
  inherited;
  if Container.Pressed[keyA] then 
    KeepMoving;
end;

in the Update method. See Designing user interface and handling events (press, update) within the view | Manual | Castle Game Engine for documentation of this.

In contrast, if you want to know when user presses the key, override the Press method (this is also shown in Designing user interface and handling events (press, update) within the view | Manual | Castle Game Engine ). The Press is called

  • when user first presses the key,

  • it also gets called in further frames (when user keeps holding a key) with frequency specific to given user’s configuration. This is the “key repeat” mechanism of your graphic system, this is why when you press “a” in a text editor and hold it, eventually you will write “aaaaaaaaaaaaaaaaaaaaa…”. If you’re not interested in this, just check TInputPressRelease.KeyRepeated. So e.g. in Press method, if you want to react only to when user physically starts pressing a key, you can check

    function TViewMain.Press(const Event: TInputPressRelease): Boolean;
    begin
      Result := inherited;
      if Result then Exit; // allow the ancestor to handle keys
      if Event.IsKey(keyA) and not Event.KeyRepeated then
        DoSomething;
    end;
    
1 Like