core/inputactions
입력 동작.
- 원본 core/inputactions.js 를 옮겼다. 동작 이름("confirm", "left" 같은 게임이 정한 글)에 키, 게임패드 단추, 게임패드 축의 한쪽을 묶는다. 한 동작에 여럿을 묶을 수 있고, 하나라도 눌렸으면 눌린 것이다.
- 엔진의 InputManager 가 하나 들고(get_input_actions) 프레임 첫머리의 tick 에서 update 를 부른다. 게임은 읽기만 한다.
- 키는 프레임 사이에 눌렀다 뗀 것도 그 프레임에 한 번 눌린 것으로 본다. (InputManager.is_key_just_pressed)
- set_repeat 를 건 동작은 누르고 있으면 기다린 뒤부터 간격마다 is_just_pressed 가 다시 참이 된다. (메뉴 고르기)
- 축은 죽은 구역(set_dead_zone)을 빼고 나머지를 0 ~ 1 로 다시 편다. 스틱은 길이로, 묶은 축은 한쪽 값으로 거른다.
- 바깥 입력원(add_source)은 엔진이 모르는 입력(플랫폼 SDK 의 패드 같은 것)을 게임이 끼우는 자리다. InputActionSource 트레이트를 단다.
- 글자 입력칸에 쓰는 동안은 키를 듣지 않는다. (set_keys_ignored_while_typing 으로 끈다)
- 유니티 Input System 처럼 프레임 처음의 update 에서 한 번 갱신하고, 그 프레임 안의 읽기는 그때 적은 값이다. (원본과 같다) update 때 이동 키, 패드 축, 바깥 입력원의 이동 축을 적어 두고 read_gamepad_stick, read_move_axis 가 그 값을 읽는다.
- 원본과 다른 점: 바깥 입력원은 JS 객체 대신 트레이트이고, 빼기는 add_source 가 준 번호로 한다.
Input actions.
- A port of the original core/inputactions.js. Binds keys, gamepad buttons and one side of gamepad axes to action names (text the game chooses, like "confirm" or "left"). Several can be bound to one action, and it is pressed if any one of them is pressed.
- The engine's InputManager holds one (get_input_actions) and calls update in tick at the start of the frame. The game only reads.
- A key pressed and released between frames also counts as pressed once in that frame. (InputManager.is_key_just_pressed)
- For an action with set_repeat, while held, is_just_pressed becomes true again at each interval after the wait. (menu selection)
- Axes subtract the dead zone (set_dead_zone) and rescale the rest to 0 ~ 1. Sticks are filtered by length, bound axes by one side's value.
- External sources (add_source) are where the game plugs in input the engine does not know (such as a platform SDK's pad). They implement the InputActionSource trait.
- Keys are not listened to while typing in a text input. (turned off with set_keys_ignored_while_typing)
- Like the Unity Input System, it updates once in update at the start of the frame, and reads within that frame return the values recorded then. (same as the original) During update it records the move keys, pad axes and external sources' move axes, and read_gamepad_stick and read_move_axis read those values.
- Differences from the original: external sources are a trait instead of JS objects, and removal uses the number given by add_source.
InputActionSourcetrait
바깥 입력원. (게임이 플랫폼 SDK 의 패드 같은 것을 끼울 때 단다)
- InputActions.update 가 프레임마다 묶어 둔 동작마다 read_action_value 를 부르고, 한 번 read_move_axis 를 부른다.
External input source. (implemented when the game plugs in something like a platform SDK's pad)
- InputActions.update calls read_action_value for each bound action every frame, and calls read_move_axis once.
use vanilla::{GamepadKind, InputActionSource, InputActions, InputManager, Vector2};
struct ScriptedSource;
impl InputActionSource for ScriptedSource {
fn read_action_value(&mut self, action: &str) -> f64 {
if action == "confirm" {
1.0
}
else {
0.0
}
}
fn read_move_axis(&mut self) -> Option<Vector2> {
Some(Vector2::create(2.0, 0.0))
}
fn read_gamepad_kind(&mut self) -> Option<GamepadKind> {
Some(GamepadKind::Nintendo)
}
}
let mut input_manager = InputManager::new();
let mut input_actions = InputActions::new();
input_actions.bind_key("confirm", "Enter");
input_actions.add_source(Box::new(ScriptedSource));
input_actions.update(&mut input_manager, 1.0 / 60.0);
assert!(input_actions.is_pressed("confirm"));
assert_eq!(input_actions.read_move_axis(), Vector2::create(1.0, 0.0));
assert_eq!(input_manager.get_last_gamepad_kind(), GamepadKind::Nintendo);동작의 값. (0 ~ 1, 0.5 이상이면 눌림, 모르는 동작이면 0)
Value of the action. (0 ~ 1, pressed at 0.5 or more, 0 for an unknown action)
- action&str
- 동작 이름. (bind_key 들이나 set_repeat 로 적어 둔 것)Action name. (one recorded with bind_key and the like or set_repeat)
반환Returnsf64 그 동작의 값. (0 ~ 1 로 자르고, 수가 아니면 0 으로 본다)Value of that action. (clamped to 0 ~ 1, treated as 0 if not a number)
이동 축. (오른쪽 +x 아래 +y, 길이 1 이하로 자른다, 없으면 None)
Move axis. (right +x down +y, clamped to length 1 or less, None if absent)
반환ReturnsOption<Vector2> 이번 프레임의 이동 방향. 이 입력원에 이동 축이 없으면 None. (기본 구현은 None)Move direction for this frame. None if this source has no move axis. (the default implementation returns None)
이 입력원이 입력을 넣은 프레임에 마지막 장치로 적을 패드 종류. (None 이면 적지 않는다)
Pad type to record as the last device in a frame where this source gave input. (not recorded if None)
반환ReturnsOption<GamepadKind> 패드 종류. 동작 값이 0.5 이상이거나 이동 축이 죽은 구역보다 길 때만 묻는다. (기본 구현은 None)Pad type. Asked only when an action value is 0.5 or more or the move axis is longer than the dead zone. (the default implementation returns None)
InputActionsstruct traits Default
입력 동작.
- 동작은 bind_key, bind_gamepad_button, bind_axis, set_repeat 가운데 하나로 한 번 적어 둔 것만 갱신한다.
Input actions.
- Only actions recorded once with one of bind_key, bind_gamepad_button, bind_axis or set_repeat are updated.
use vanilla::{InputActions, InputManager, KeyCode};
let mut input_manager = InputManager::new();
let mut input_actions = InputActions::new();
input_actions.bind_key("jump", KeyCode::SPACE);
input_actions.bind_key("jump", KeyCode::W);
input_manager.push_key(KeyCode::W);
input_actions.update(&mut input_manager, 1.0 / 60.0);
assert!(input_actions.is_just_pressed("jump"));
assert_eq!(input_actions.read_value("jump"), 1.0);
assert_eq!(input_actions.read_move_axis().y, -1.0);use vanilla::{Engine, EngineConfiguration, GamepadButtonCode, KeyCode, Scene, SceneBase};
struct MainScene {
scene_base: SceneBase,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn load(&mut self, engine: &Engine) {
let mut input_manager = engine.get_input_manager_mut();
let mut input_actions = input_manager.get_input_actions_mut();
input_actions.bind_key("confirm", KeyCode::ENTER);
input_actions.bind_gamepad_button("confirm", GamepadButtonCode::A_CROSS);
}
fn tick(&mut self, time_delta: f64) {
let engine = Engine::get_engine().unwrap();
self.scene_base.tick(time_delta);
let input_manager = engine.get_input_manager();
let input_actions = input_manager.get_input_actions();
if input_actions.is_just_pressed("confirm") {
println!("confirm");
}
let move_axis = input_actions.read_move_axis();
println!("{} {}", move_axis.x, move_axis.y);
}
}
let engine_configuration = EngineConfiguration::new();
let engine = Engine::new(engine_configuration);
let main_scene = MainScene {
scene_base: SceneBase::new(),
};
engine.run(Box::new(main_scene)).unwrap();생성.
Constructor.
반환ReturnsInputActions 묶은 것이 없는 입력 동작. (죽은 구역 0.2, 축 눌림 기울기 0.5, 글자 입력 중 키 무시 켬)Input actions with nothing bound. (dead zone 0.2, axis press tilt 0.5, ignoring keys while typing on)
짝Counterpart: vanilla.js InputActions.constructor
키 묶기. (KeyboardEvent.code, KeyCode 의 값)
- 같은 키를 두 번 묶어도 하나다.
Binds a key. (KeyboardEvent.code, a KeyCode value)
- Binding the same key twice still counts as one.
- action&str
- 동작 이름. (게임이 정한 글)Action name. (text chosen by the game)
- key&str
- 키 이름. (KeyCode 의 값)Key name. (a KeyCode value)
짝Counterpart: vanilla.js InputActions.bindKey
게임패드 단추 묶기. (GamepadButtonCode, 연결된 패드 모두)
- 값(read_value)은 그 단추의 아날로그 값이고, 0 이면 1 로 본다.
Binds a gamepad button. (GamepadButtonCode, all connected pads)
- The value (read_value) is the button's analog value, treated as 1 if 0.
- action&str
- 동작 이름.Action name.
- button_codeusize
- 버튼 번호. (GamepadButtonCode)Button index. (GamepadButtonCode)
짝Counterpart: vanilla.js InputActions.bindGamepadButton
게임패드 축의 한쪽 묶기. (GamepadAnalogStickCode, direction 이 양수면 + 쪽, 음수면 - 쪽, 축 Y 는 아래가 +)
- 그쪽으로 set_axis_press_threshold 만큼 기울면 눌린 것이고, 값(read_value)은 죽은 구역을 뺀 기울기다.
Binds one side of a gamepad axis. (GamepadAnalogStickCode, the + side if direction is positive, the - side if negative, down is + on the Y axis)
- It is pressed when tilted that way by set_axis_press_threshold, and the value (read_value) is the tilt with the dead zone subtracted.
- action&str
- 동작 이름.Action name.
- axis_indexusize
- 축 번호. (GamepadAnalogStickCode)Axis number. (GamepadAnalogStickCode)
- directionf64
- 볼 쪽. (음수면 - 쪽, 0 이나 양수면 + 쪽, 크기는 쓰지 않는다)Side to watch. (the - side if negative, the + side if 0 or positive, the magnitude is not used)
짝Counterpart: vanilla.js InputActions.bindAxis
use vanilla::{Gamepad, GamepadAnalogStickCode, InputActions, InputManager};
let mut input_manager = InputManager::new();
input_manager.get_gamepad_manager_mut().set_log_enabled(false);
let mut gamepad = Gamepad::create(0, "Test Pad");
gamepad.axes[GamepadAnalogStickCode::LEFT_X] = -0.6;
input_manager.get_gamepad_manager_mut().update_all_gamepads_with_list(vec![Some(gamepad)]);
let mut input_actions = InputActions::new();
input_actions.bind_axis("left", GamepadAnalogStickCode::LEFT_X, -1.0);
input_actions.update(&mut input_manager, 1.0 / 60.0);
assert!(input_actions.is_pressed("left"));
assert!((input_actions.read_value("left") - 0.5).abs() < 0.0001);동작에 묶은 것 모두 풀기. (키 바꾸기 화면에서 다시 묶기 전에, 반복 설정은 남는다)
Unbinds everything bound to an action. (before rebinding in a key remapping screen, repeat settings remain)
- action&str
- 동작 이름.Action name.
짝Counterpart: vanilla.js InputActions.unbindAction
use vanilla::{InputActions, KeyCode};
let mut input_actions = InputActions::new();
input_actions.bind_key("confirm", KeyCode::ENTER);
input_actions.unbind_action("confirm");
input_actions.bind_key("confirm", KeyCode::SPACE);
assert_eq!(input_actions.get_bound_keys("confirm"), ["Space"]);동작에 묶은 키 목록. (단추 안내를 그릴 때)
List of keys bound to the action. (for drawing button hints)
- action&str
- 동작 이름.Action name.
반환Returns&[String] 묶은 차례의 키 이름들. 묶은 키가 없으면 빈 조각.Key names in bind order. An empty slice if no keys are bound.
짝Counterpart: vanilla.js InputActions.getBoundKeys
누르고 있으면 반복 설정. (기다리는 초 뒤부터 간격 초마다 is_just_pressed 가 참, 간격이 0 이하면 반복을 끈다)
- 프레임이 길게 끊겨도 반복을 몰아서 하지 않는다.
Sets repeat while held. (is_just_pressed is true every interval seconds after the wait seconds, an interval of 0 or less turns repeat off)
- Repeats are not bunched up even if a frame stalls for a long time.
- action&str
- 동작 이름.Action name.
- delay_secondsf64
- 첫 누름 뒤 반복을 시작할 때까지 기다리는 초. (음수는 0)Seconds to wait after the first press before repeating starts. (negative values become 0)
- interval_secondsf64
- 반복 간격 초. (0 이하면 반복을 끈다)Repeat interval in seconds. (0 or less turns repeat off)
짝Counterpart: vanilla.js InputActions.setRepeat
use vanilla::{InputActions, InputManager, KeyCode};
let mut input_manager = InputManager::new();
let mut input_actions = InputActions::new();
input_actions.bind_key("right", KeyCode::RIGHT);
input_actions.set_repeat("right", 0.25, 0.1);
input_manager.push_key(KeyCode::RIGHT);
let mut just_pressed_count = 0;
for _ in 0..60 {
input_actions.update(&mut input_manager, 1.0 / 60.0);
if input_actions.is_just_pressed("right") {
just_pressed_count += 1;
}
input_manager.update_frame_snapshot();
}
assert_eq!(just_pressed_count, 9);죽은 구역 설정. (0 ~ 1 미만, 처음은 0.2)
Sets the dead zone. (0 ~ less than 1, initially 0.2)
- dead_zonef64
- 이보다 덜 기울면 0 으로 보는 길이. (0 ~ 0.99 로 자른다)Length below which a tilt counts as 0. (clamped to 0 ~ 0.99)
짝Counterpart: vanilla.js InputActions.setDeadZone
죽은 구역.
Dead zone.
반환Returnsf64 지금 죽은 구역. (0 ~ 0.99, 처음은 0.2)Current dead zone. (0 ~ 0.99, initially 0.2)
짝Counterpart: vanilla.js InputActions.getDeadZone
축에 묶은 동작을 눌린 것으로 보는 기울기 설정. (0 ~ 1, 처음은 0.5)
Sets the tilt at which an axis-bound action counts as pressed. (0 ~ 1, initially 0.5)
- axis_press_thresholdf64
- 눌림으로 볼 기울기. (죽은 구역을 빼기 전 값, 0 ~ 1 로 자른다)Tilt that counts as pressed. (value before subtracting the dead zone, clamped to 0 ~ 1)
짝Counterpart: vanilla.js InputActions.setAxisPressThreshold
축에 묶은 동작을 눌린 것으로 보는 기울기.
Tilt at which an action bound to an axis counts as pressed.
반환Returnsf64 지금 기울기. (0 ~ 1, 처음은 0.5)Current tilt. (0 ~ 1, initially 0.5)
짝Counterpart: vanilla.js InputActions.getAxisPressThreshold
글자 입력칸에 쓰는 동안 키를 듣지 않을지 설정. (처음은 참)
Sets whether keys are ignored while typing in a text field. (initially true)
- is_ignoredbool
- 쓰는 동안 키(동작의 키와 이동 키)를 듣지 않으려면 true.true to not listen to keys (action keys and move keys) while typing.
짝Counterpart: vanilla.js InputActions.setKeysIgnoredWhileTyping
글자 입력칸에 쓰는 동안 키를 듣지 않는지.
Whether keys are not listened to while typing in a text input.
반환Returnsbool 듣지 않으면 true. (처음은 true)true if not listening. (initially true)
짝Counterpart: vanilla.js InputActions.isKeysIgnoredWhileTyping
바깥 입력원 더하기. (돌려주는 번호로 remove_source 한다)
Adds an external input source. (remove_source with the returned number)
- sourceBox<dyn InputActionSource>
- 끼울 입력원.Source to plug in.
반환Returnsu64 이 입력원의 번호. (1 부터 더할 때마다 하나씩 커진다)Number of this source. (starts at 1 and grows by one with each add)
짝Counterpart: vanilla.js InputActions.addSource
use vanilla::{InputActionSource, InputActions};
struct SilentSource;
impl InputActionSource for SilentSource {
fn read_action_value(&mut self, _action: &str) -> f64 {
0.0
}
}
let mut input_actions = InputActions::new();
let source_id = input_actions.add_source(Box::new(SilentSource));
assert!(input_actions.remove_source(source_id));
assert!(!input_actions.remove_source(source_id));바깥 입력원 빼기. (있었으면 true)
Removes an external input source. (true if it was there)
- source_idu64
- add_source 가 돌려준 번호.Number returned by add_source.
반환Returnsbool 그 번호의 입력원이 있어 뺐으면 true, 없으면 false.true if a source with that number existed and was removed, false otherwise.
짝Counterpart: vanilla.js InputActions.removeSource
프레임마다 갱신. (InputManager.tick 이 부른다)
- 바깥 입력원이 입력을 넣었으면 input_manager 의 마지막 장치를 그 패드로 적는다.
Per-frame update. (called by InputManager.tick)
- If an external source gave input, records that pad as the last device of input_manager.
- input_manager&mut InputManager
- 키와 게임패드를 읽을 입력 관리자.Input manager to read keys and gamepads from.
- time_deltaf64
- 지난 갱신 뒤로 흐른 초. (반복 시간을 센다)Seconds elapsed since the last update. (counts repeat time)
짝Counterpart: vanilla.js InputActions.update
모두 뗀 것으로 되돌리기. (창이 포커스를 잃었을 때, 뗌도 알리지 않는다)
Resets everything to released. (when the window loses focus, releases are not reported either)
짝Counterpart: vanilla.js InputActions.clear
동작이 눌려 있는지.
Whether the action is held.
- action&str
- 동작 이름.Action name.
반환Returnsbool 묶은 키, 단추, 축, 바깥 입력원 가운데 하나라도 눌렸으면 true. 모르는 동작이면 false.true if any bound key, button, axis or external source is pressed. false for an unknown action.
짝Counterpart: vanilla.js InputActions.isPressed
이번 프레임에 눌렸는지. (set_repeat 를 건 동작은 반복 때도 참)
Whether it was pressed this frame. (also true on repeats for actions with set_repeat)
- action&str
- 동작 이름.Action name.
반환Returnsbool 지난 갱신에 떼어 있다가 이번 갱신에 눌렸거나 반복이 났으면 true. 모르는 동작이면 false.true if it was released at the last update and pressed at this update, or a repeat fired. false for an unknown action.
짝Counterpart: vanilla.js InputActions.isJustPressed
이번 프레임에 떼어졌는지.
Whether it was released this frame.
- action&str
- 동작 이름.Action name.
반환Returnsbool 지난 갱신에 눌려 있다가 이번 갱신에 떼어졌으면 true. 모르는 동작이면 false.true if it was pressed at the last update and released at this update. false for an unknown action.
짝Counterpart: vanilla.js InputActions.isJustReleased
동작의 값. (0 ~ 1, 키와 디지털 단추는 1, 트리거와 축은 기운 만큼)
The action's value. (0 ~ 1, 1 for keys and digital buttons, triggers and axes by how far they are tilted)
- action&str
- 동작 이름.Action name.
반환Returnsf64 묶은 것 가운데 가장 큰 값. (0 ~ 1, 축은 죽은 구역을 빼고 다시 편 값) 모르는 동작이면 0.Largest value among the bindings. (0 ~ 1, axes are the value with the dead zone subtracted and rescaled) 0 for an unknown action.
짝Counterpart: vanilla.js InputActions.readValue
두 동작으로 만든 축. (-1 ~ 1, 양쪽 동작의 값의 차)
An axis made from two actions. (-1 ~ 1, the difference between the two actions' values)
- negative_action&str
- - 쪽 동작 이름. ("left" 같은)Name of the - side action. (like "left")
- positive_action&str
- + 쪽 동작 이름. ("right" 같은)Name of the + side action. (like "right")
반환Returnsf64 positive_action 의 값에서 negative_action 의 값을 뺀 것. (둘 다 눌리면 0 에 가깝다)Value of positive_action minus the value of negative_action. (close to 0 if both are pressed)
짝Counterpart: vanilla.js InputActions.readAxis
use vanilla::{InputActions, InputManager, KeyCode};
let mut input_manager = InputManager::new();
let mut input_actions = InputActions::new();
input_actions.bind_key("left", KeyCode::LEFT);
input_actions.bind_key("right", KeyCode::RIGHT);
input_manager.push_key(KeyCode::LEFT);
input_actions.update(&mut input_manager, 1.0 / 60.0);
assert_eq!(input_actions.read_axis("left", "right"), -1.0);게임패드 스틱. (연결된 패드 가운데 가장 크게 기운 것, 죽은 구역을 길이로 빼고 길이 1 이하, 오른쪽 +x 아래 +y)
- 마지막 update 때 적어 둔 값을 읽는다. 축 번호는 0 ~ 3 만 적어 둔다.
Gamepad stick. (the most tilted among connected pads, dead zone subtracted by length, length 1 or less, right +x down +y)
- Reads the values recorded at the last update. Only axis numbers 0 ~ 3 are recorded.
- x_axis_indexusize
- 가로 축 번호. (GamepadAnalogStickCode::LEFT_X 나 RIGHT_X)Horizontal axis number. (GamepadAnalogStickCode::LEFT_X or RIGHT_X)
- y_axis_indexusize
- 세로 축 번호. (GamepadAnalogStickCode::LEFT_Y 나 RIGHT_Y)Vertical axis number. (GamepadAnalogStickCode::LEFT_Y or RIGHT_Y)
반환ReturnsVector2 스틱 방향과 죽은 구역을 뺀 길이. (연결된 패드가 없거나 죽은 구역 안이면 0, 0)Stick direction and length with the dead zone subtracted. (0, 0 if no pad is connected or inside the dead zone)
짝Counterpart: vanilla.js InputActions.readGamepadStick
use vanilla::{Gamepad, GamepadAnalogStickCode, InputActions, InputManager};
let mut input_manager = InputManager::new();
input_manager.get_gamepad_manager_mut().set_log_enabled(false);
let mut gamepad = Gamepad::create(0, "Test Pad");
gamepad.axes[GamepadAnalogStickCode::RIGHT_Y] = 1.0;
input_manager.get_gamepad_manager_mut().update_all_gamepads_with_list(vec![Some(gamepad)]);
let mut input_actions = InputActions::new();
input_actions.update(&mut input_manager, 1.0 / 60.0);
let stick = input_actions.read_gamepad_stick(GamepadAnalogStickCode::RIGHT_X, GamepadAnalogStickCode::RIGHT_Y);
assert_eq!(stick.x, 0.0);
assert!((stick.y - 1.0).abs() < 0.0001);이동 축. (WASD 와 방향키, 왼쪽 스틱, 바깥 입력원의 이동 축 가운데 가장 긴 것, 길이 1 이하, 오른쪽 +x 아래 +y)
- 키는 대각선도 길이 1 이다. 글자 입력칸에 쓰는 동안은 키를 듣지 않는다.
Movement axis. (the longest of WASD and arrow keys, the left stick, and external sources' movement axes, length 1 or less, right +x down +y)
- Keys have length 1 diagonally too. Keys are not listened to while typing in a text field.
반환ReturnsVector2 이동 방향. (길이 0 ~ 1, 마지막 update 때의 값)Move direction. (length 0 ~ 1, the value at the last update)
짝Counterpart: vanilla.js InputActions.readMoveAxis
use vanilla::{InputActions, InputManager, KeyCode};
let mut input_manager = InputManager::new();
let mut input_actions = InputActions::new();
input_manager.push_key(KeyCode::W);
input_manager.push_key(KeyCode::D);
input_actions.update(&mut input_manager, 1.0 / 60.0);
let move_axis = input_actions.read_move_axis();
assert!((move_axis.x - std::f64::consts::FRAC_1_SQRT_2).abs() < 0.0001);
assert!((move_axis.y + std::f64::consts::FRAC_1_SQRT_2).abs() < 0.0001);