Как пользоваться input manager в unity

от admin

Input Manager

The Input Manager window allows you to define input axes and their associated actions for your Project. To access it, from Unity’s main menu, go to Edit > Project Settings, then select Input Manager from the navigation on the right.

The Input Manager uses the following types of controls:

  • Key refers to any key on a physical keyboard, such as W, Shift, or the space bar.
  • Button refers to any button on a physical controller (for example, gamepads), such as the X button on a remote control.
  • A virtual axis (plural: axes) is mapped to a control, such as a button or a key. When the user activates the control, the axis receives a value in the range of [–1..1]. You can use this value in your scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
    See in Glossary .

Physical keys

The Physical keys option allows you to map key codes to the physical keyboard layout, rather than to the language-specific layout that may vary between users in different regions.

For example, on some keyboards the first row of letters reads “QWERTY”, and on others it reads “AZERTY”. This means if you scripted specific controls to use the well known “WASD” keys for movement, they would not be in the correct physical arrangement (like the arrow-key arrangement) on an AZERTY-layout keyboard.

With Physical Keys enabled, Unity uses a generic ANSI/ISO “Qwerty” layout to represent the physical location of the keys regardless of the user’s actual layout. This means if you specify the “Q” key, it will always be the left-most letter on the first row of letter keys, even if the user’s keyboard has a different letter in that position.

Note, you should not read key input for in-game text input, because this will not allow users to enter non-Latin characters. Instead, use Input.compositionString .

Virtual axes

Every Project you create has a number of input axes created by default. These axes enable you to use keyboard, mouse, and joystick input in your Project straight away.

To see more about these axes, open the Input Manager window, and click the arrow next to any axis name to expand its properties.

Each input axis has the following properties:

Axis values can be:

  • Between –1 and 1 for joystick and keyboard input. The neutral position for these axes is 0. Some types of controls, such as buttons on a keyboard, aren’t sensitive to input intensity, so they can’t produce values other than –1, 0, or 1.
  • Mouse delta (how much the mouse has moved during the last frame) for mouse input. The values for mouse input axes can be larger than 1 or smaller than –1 when the user moves the mouse quickly.

Adding, removing, and copying virtual axes

To add a virtual axis, increase the number in the Size field. This creates a new axis at the bottom of the list. The new axis copies the properties of the previous axis in the list.

To remove a virtual axis, you can either:

  • Decrease the number in the Size field. This removes the last axis in the list.
  • Right-click any axis, and select Delete Array Element.
    Note: You can’t undo this action.

To copy a virtual axis, right-click it and select Duplicate Array Element.

Mapping virtual axes to controls

To map a key or button to an axis, enter its name in the Positive Button or Negative Button property in the Input Manager.

Key names follow these naming conventions:

Key family Naming convention
Letter keys a , b , c …
Number keys 1 , 2 , 3 …
Arrow keys up , down , left , right
Numpad keys [1] , [2] , [3] , [+] , [equals] …
Modifier keys right shift , left shift , right ctrl , left ctrl , right alt , left alt , right cmd , left cmd
Special keys backspace , tab , return , escape , space , delete , enter , insert , home , end , page up , page down
Function keys f1 , f2 , f3 …

Mouse buttons are named mouse 0, mouse 1, mouse 2, and so on.

Joystick buttons follow these naming conventions:

Button origin Naming convention
A specific button on any joystick joystick button 0 , joystick button 1 , joystick button 2 …
A specific button on a specific joystick joystick 1 button 0 , joystick 1 button 1 , joystick 2 button 0 …

You can also query input for a specific key or button with Input.GetKey and the naming conventions specified above. For example:

Another way to access keys is to use the KeyCode enumeration.

Using virtual axes in scripts

To access virtual axes from scripts, you can use the axis name.

For example, to query the current value of the Horizontal axis and store it in a variable, you can use Input.GetAxis like this:

For axes that describe an event rather than a movement (for example, firing a weapon in a game), use Input.GetButtonDown instead.

If two or more axes have the same name, the query returns the axis with the largest absolute value. This makes it possible to assign more than one input device to an axis name.

For example, you can create two axes named Horizontal and assign one to keyboard input and the other to joystick input. If the user is using the joystick, input comes from the joystick and keyboard input is null. Otherwise, input comes from the keyboard and joystick input is null. This enables you to write a single script that covers input from multiple controllers.

Input Manager

The Input Manager window allows you to define input axes and their associated actions for your Project. To access it, from Unity’s main menu, go to Edit > Project Settings, then select Input Manager from teh navigation on the right.

The Input Manager uses the following types of controls:

  • Key refers to any key on a physical keyboard, such as W, Shift, or the space bar.
  • Button refers to any button on a physical controller (for example, gamepads), such as the X button on an Xbox One controller.
  • A virtual axis (plural: axes) is mapped to a control, such as a button or a key. When the user activates the control, the axis receives a value in the range of [–1..1]. You can use this value in your scripts.

Virtual axes

Every Project you create has a number of input axes created by default. These axes enable you to use keyboard, mouse, and joystick input in your Project straight away.

To see more about these axes, open the Input Manager window, and click the arrow next to any axis name to expand its properties.

Each input axis has the following properties:

Axis values can be:

  • Between –1 and 1 for joystick and keyboard input. The neutral position for these axes is 0. Some types of controls, such as buttons on a keyboard, aren’t sensitive to input intensity, so they can’t produce values other than –1, 0, or 1.
  • Mouse delta (how much the mouse has moved during the last frame) for mouse input. The values for mouse input axes can be larger than 1 or smaller than –1 when the user moves the mouse quickly.

Adding, removing, and copying virtual axes

To add a virtual axis, increase the number in the Size field. This creates a new axis at the bottom of the list. The new axis copies the properties of the previous axis in the list.

To remove a virtual axis, you can either:

  • Decrease the number in the Size field. This removes the last axis in the list.
  • Right-click any axis, and select Delete Array Element.
    Note: You can’t undo this action.

To copy a virtual axis, right-click it and select Duplicate Array Element.

Mapping virtual axes to controls

To map a key or button to an axis, enter its name in the Positive Button or Negative Button property in the Input Manager.

Key names follow these naming conventions:

Key family Naming convention
Letter keys a , b , c …
Number keys 1 , 2 , 3 …
Arrow keys up , down , left , right
Numpad keys [1] , [2] , [3] , [+] , [equals] …
Modifier keys right shift , left shift , right ctrl , left ctrl , right alt , left alt , right cmd , left cmd
Special keys backspace , tab , return , escape , space , delete , enter , insert , home , end , page up , page down
Function keys f1 , f2 , f3 …

Mouse buttons are named mouse 0, mouse 1, mouse 2, and so on.

Joystick buttons follow these naming conventions:

Button origin Naming convention
A specific button on any joystick joystick button 0 , joystick button 1 , joystick button 2 …
A specific button on a specific joystick joystick 1 button 0 , joystick 1 button 1 , joystick 2 button 0 …

You can also query input for a specific key or button with Input.GetKey and the naming conventions specified above. For example:

Another way to access keys is to use the KeyCode enumeration.

Using virtual axes in scripts

To access virtual axes from scripts, you can use the axis name.

For example, to query the current value of the Horizontal axis and store it in a variable, you can use Input.GetAxis like this:

For axes that describe an event rather than a movement (for example, firing a weapon in a game), use Input.GetButtonDown instead.

If two or more axes have the same name, the query returns the axis with the largest absolute value. This makes it possible to assign more than one input device to an axis name.

For example, you can create two axes named Horizontal and assign one to keyboard input and the other to joystick input. If the user is using the joystick, input comes from the joystick and keyboard input is null. Otherwise, input comes from the keyboard and joystick input is null. This enables you to write a single script that covers input from multiple controllers.

Input менеджер

Окно Диспетчер ввода позволяет определить оси ввода и связанные с ними действия для вашего проекта. Чтобы получить к нему доступ, в главном меню Unity выберите Правка > Настройки проекта, затем выберите Диспетчер ввода на панели навигации справа.

Диспетчер ввода использует следующие типы элементов управления:

  • Клавиша — это любая клавиша на физической клавиатуре, например W, Shift или пробел.
  • Под кнопкой понимается любая кнопка на физическом контроллере (например, геймпадах), например кнопка X на контроллере Xbox One.
  • Виртуальная ось (во множественном числе: оси) сопоставляется с элементом управления, например кнопкой или клавишей. Когда пользователь активирует элемент управления, ось получает значение в диапазоне [–1..1]. Вы можете использовать это значение в своих скриптах фрагмент кода, позволяющий создавать собственные компоненты, запускать игровые события, изменять компоненты свойства с течением времени и реагировать на пользовательский ввод любым удобным для вас способом. Подробнее
    См. в Словарь .

Виртуальные оси

Каждый проект, который вы создаете, имеет ряд входных осей, созданных по умолчанию. Эти оси позволяют сразу использовать ввод с клавиатуры, мыши и джойстика в проекте.

Чтобы узнать больше об этих осях, откройте окно Диспетчер ввода и щелкните стрелку рядом с именем любой оси, чтобы развернуть ее свойства.

Каждая ось ввода имеет следующие свойства:

— Клавиша или кнопка мыши
— Движение мыши
— Ось джойстика

Значения оси могут быть:

  • От –1 до 1 для джойстика и ввода с клавиатуры. Нейтральное положение для этих осей — 0. Некоторые типы элементов управления, например кнопки на клавиатуре, не чувствительны к интенсивности ввода, поэтому они не могут выдавать значения, отличные от –1, 0 или 1.
  • Дельта мыши (насколько мышь переместилась в течение последнего кадра) для ввода с помощью мыши. Значения для осей ввода мыши могут быть больше 1 или меньше –1, когда пользователь быстро перемещает мышь.

Добавление, удаление и копирование виртуальных осей

Чтобы добавить виртуальную ось, увеличьте число в поле Размер. Это создает новую ось внизу списка. Новая ось копирует свойства предыдущей оси в списке.

Чтобы удалить виртуальную ось, вы можете:

  • Уменьшите число в поле Размер. Это удалит последнюю ось в списке.
  • Нажмите правой кнопкой мыши любую ось и выберите Удалить элемент массива.
    Примечание. Это действие нельзя отменить.

Чтобы скопировать виртуальную ось, щелкните ее правой кнопкой мыши и выберите Дублировать элемент массива.

Сопоставление виртуальных осей с элементами управления

Чтобы сопоставить клавишу или кнопку с осью, введите ее имя в свойство Положительная кнопка или Отрицательная кнопка в Диспетчере ввода.

Названия ключей соответствуют следующим соглашениям об именах:

Key family Соглашение об именовании
Letter keys a , b , c …
Number keys 1 , 2 , 3 …
Arrow keys up , down , left , right
Numpad keys [1] , [2] , [3] , [+] , [equals] …
Modifier keys right shift , left shift , right ctrl , left ctrl , right alt , left alt , right cmd , left cmd
Special keys backspace , tab , return , escape , space , delete , enter , insert , home , end , page up , page down
Function keys f1 , f2 , f3 …

Кнопки мыши называются mouse 0, mouse 1, mouse 2 и т. д.

Кнопки джойстика имеют следующие соглашения об именах:

Происхождение кнопки Соглашение об именовании
A specific button on any joystick joystick button 0 , joystick button 1 , joystick button 2 …
A specific button on a specific joystick joystick 1 button 0 , joystick 1 button 1 , joystick 2 button 0 …

Вы также можете запросить ввод для определенной клавиши или кнопки с помощью Input.GetKey и соглашения об именах, указанные выше. Например:

Еще один способ получить доступ к ключам — использовать перечисление KeyCode .

Использование виртуальных осей в скриптах

Чтобы получить доступ к виртуальным осям из сценариев, вы можете использовать имя оси.

Например, чтобы запросить текущее значение горизонтальной оси и сохранить его в переменной, можно использовать Input. GetAxis вот так:

float horizontalInput = Input.GetAxis(«Horizontal»);

Для осей, которые описывают событие, а не движение (например, стрельба из оружия в игре), используйте Input .GetButtonDown вместо этого.

Если две или более осей имеют одинаковое имя, запрос возвращает ось с наибольшим абсолютным значением. Это позволяет присвоить имени оси более одного устройства ввода.

Например, вы можете создать две оси с именем Горизонтальная и назначить одну для ввода с клавиатуры, а другую — для ввода с помощью джойстика. Если пользователь использует джойстик, ввод осуществляется с джойстика, а ввод с клавиатуры невозможен. В противном случае ввод осуществляется с клавиатуры, а ввод с джойстика невозможен. Это позволяет вам написать один сценарий, охватывающий ввод с нескольких контроллеров.

Web server is returning an unknown error Error code 520

There is an unknown connection issue between Cloudflare and the origin web server. As a result, the web page can not be displayed.

What can I do?

If you are a visitor of this website:

Please try again in a few minutes.

If you are the owner of this website:

There is an issue between Cloudflare’s cache and your origin web server. Cloudflare monitors for these errors and automatically investigates the cause. To help support the investigation, you can pull the corresponding error log from your web server and submit it our support team. Please include the Ray ID (which is at the bottom of this error page). Additional troubleshooting resources.

Cloudflare Ray ID: 7a762379a51a2301 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

Читать:
Что такое перегрузка операторов

Похожие статьи