- Mobile device input
- Multi-touch screen
- Mouse simulation
- Accelerometer
- Low-Pass Filter
- I’d like as much precision as possible when reading the accelerometer. What should I do?
- Conventional Game Input
- Virtual Axes
- Adding new Input Axes
- Using Input Axes from Scripts
- Button Names
- Ввод на мобильном устройстве
- Multi-Touch Screen
- Симуляция Мыши
- Акселерометр
- Фильтр низких частот
- Я хочу получить как можно более точные показания акселерометра. Что я должен делать?
Mobile device input
On mobile devices, the Input class offers access to touchscreen, accelerometer and geographical/location input.
Access to keyboard on mobile devices is provided via the iOS keyboard.
Multi-touch screen
The iPhone, iPad and iPod Touch devices are capable of tracking up to five fingers touching the screen simultaneously. You can retrieve the status of each finger touching the screen during the last frame by accessing the Input.touches property array.
Android devices don’t have a unified limit on how many fingers they track. Instead, it varies from device to device and can be anything from two-touch on older devices to five fingers on some newer devices.
Each finger touch is represented by an Input.Touch data structure:
Property: | Description: | |
---|---|---|
fingerId | The unique index for a touch. | |
position | The screen position of the touch. | |
deltaPosition | The screen position change since the last frame. | |
deltaTime | Amount of time that has passed since the last state change. | |
tapCount | The iPhone/iPad screen is able to distinguish quick finger taps by the user. This counter will let you know how many times the user has tapped the screen without moving a finger to the sides. Android devices do not count number of taps, this field is always 1. | |
phase | Describes the state of the touch, which can help you determine whether the user has just started to touch screen, just moved their finger or just lifted their finger. | |
Began | A finger just touched the screen. | |
Moved | A finger moved on the screen. | |
Stationary | A finger is touching the screen but hasn’t moved since the last frame. | |
Ended | A finger was lifted from the screen. This is the final phase of a touch. | |
Canceled | The system cancelled tracking for the touch, as when (for example) the user puts the device to their face or more than five touches happened simultaneously. This is the final phase of a touch. |
Here’s an example script that shoots a ray whenever the user taps on the screen:
Mouse simulation
On top of native touch support Unity iOS Apple’s mobile operating system. More info
See in Glossary /Android provides a mouse simulation. You can use mouse functionality from the standard Input class. Note that iOS/Android devices are designed to support multiple finger touch. Using the mouse functionality will support just a single finger touch. Also, finger touch on mobile devices can move from one area to another with no movement between them. Mouse simulation on mobile devices will provide movement, so is very different compared to touch input. The recommendation is to use the mouse simulation during early development but to use touch input as soon as possible.
Accelerometer
As the mobile device moves, a built-in accelerometer reports linear acceleration changes along the three primary axes in three-dimensional space. Acceleration along each axis is reported directly by the hardware as G-force values. A value of 1.0 represents a load of about +1g along a given axis while a value of –1.0 represents –1g. If you hold the device upright (with the home button at the bottom) in front of you, the X axis is positive along the right, the Y axis is positive directly up, and the Z axis is positive pointing toward you.
You can retrieve the accelerometer value by accessing the Input.acceleration property.
The following is an example script which will move an object using the accelerometer:
Low-Pass Filter
Accelerometer readings can be jerky and noisy. Applying low-pass filtering on the signal allows you to smooth it and get rid of high frequency noise.
The following script shows you how to apply low-pass filtering to accelerometer readings:
The greater the value of LowPassKernelWidthInSeconds , the slower the filtered value will converge towards the current input sample (and vice versa).
I’d like as much precision as possible when reading the accelerometer. What should I do?
Reading the Input.acceleration variable does not equal sampling the hardware. Put simply, Unity samples the hardware at a frequency of 60Hz and stores the result into the variable. In reality, things are a little bit more complicated – accelerometer sampling doesn’t occur at consistent time intervals, if under significant CPU loads. As a result, the system might report 2 samples during one frame, then 1 sample during the next frame.
You can access all measurements executed by accelerometer during the frame. The following code will illustrate a simple average of all the accelerometer events that were collected within the last frame:
Источник
Conventional Game Input
Unity supports keyboard, joystick and gamepad input.
Virtual axes and buttons can be created in the Input Manager, and end users can configure Keyboard input in a nice screen configuration dialog.
NOTE: This is a legacy image. This Input Selector image dates back to the very earliest versions of the Unity Editor in 2005. GooBall was a Unity Technologies game.
You can setup joysticks, gamepads, keyboard, and mouse, then access them all through one simple scripting interface. Typically you use the axes and buttons to fake up a console controller. Alternatively you can access keys on the keyboard.
Virtual Axes
From scripts, all virtual axes are accessed by their name.
Every project has the following default input axes when it’s created:
- Horizontal and Vertical are mapped to w, a, s, d and the arrow keys.
- Fire1, Fire2, Fire3 are mapped to Control, Option (Alt), and Command, respectively.
- Mouse X and Mouse Y are mapped to the delta of mouse movement.
- Window Shake X and Window Shake Y is mapped to the movement of the window.
Adding new Input Axes
If you want to add new virtual axes go to the Edit->Project Settings->Input menu. Here you can also change the settings of each axis.
You map each axis to two buttons on a joystick, mouse, or keyboard keys.
Property: | Function: |
---|---|
Name | The name of the string used to check this axis from a script. |
Descriptive Name | Positive value name displayed in the input tab of the Configuration dialog for standalone builds. |
Descriptive Negative Name | Negative value name displayed in the Input tab of the Configuration dialog for standalone builds. |
Negative Button | The button used to push the axis in the negative direction. |
Positive Button | The button used to push the axis in the positive direction. |
Alt Negative Button | Alternative button used to push the axis in the negative direction. |
Alt Positive Button | Alternative button used to push the axis in the positive direction. |
Gravity | Speed in units per second that the axis falls toward neutral when no buttons are pressed. |
Dead | Size of the analog dead zone. All analog device values within this range result map to neutral. |
Sensitivity | Speed in units per second that the the axis will move toward the target value. This is for digital devices only. |
Snap | If enabled, the axis value will reset to zero when pressing a button of the opposite direction. |
Invert | If enabled, the Negative Buttons provide a positive value, and vice-versa. |
Type | The type of inputs that will control this axis. |
Axis | The axis of a connected device that will control this axis. |
Joy Num | The connected Joystick that will control this axis. |
Use these settings to fine tune the look and feel of input. They are all documented with tooltips in the Editor as well.
Using Input Axes from Scripts
You can query the current state from a script like this:
An axis has a value between –1 and 1. The neutral position is 0. This is the case for joystick input and keyboard input.
However, Mouse Delta and Window Shake Delta are how much the mouse or window moved during the last frame. This means it can be larger than 1 or smaller than –1 when the user moves the mouse quickly.
It is possible to create multiple axes with the same name. When getting the input axis, the axis with the largest absolute value will be returned. This makes it possible to assign more than one input device to one axis name. For example, create one axis for keyboard input and one axis for joystick input with the same name. If the user is using the joystick, input will come from the joystick, otherwise input will come from the keyboard. This way you don’t have to consider where the input comes from when writing scripts.
Button Names
To map a key to an axis, you have to enter the key’s name in the Positive Button or Negative Button property in the Inspector.
The names of keys follow this convention:
- Normal keys: “a”, “b”, “c” …
- Number keys: “1”, “2”, “3”, …
- Arrow keys: “up”, “down”, “left”, “right”
- Keypad keys: “[1]”, “[2]”, “[3]”, “[+]”, “[equals]”
- Modifier keys: “right shift”, “left shift”, “right ctrl”, “left ctrl”, “right alt”, “left alt”, “right cmd”, “left cmd”
- Mouse Buttons: “mouse 0”, “mouse 1”, “mouse 2”, …
- Joystick Buttons (from any joystick): “joystick button 0”, “joystick button 1”, “joystick button 2”, …
- Joystick Buttons (from a specific joystick): “joystick 1 button 0”, “joystick 1 button 1”, “joystick 2 button 0”, …
- Special keys: “backspace”, “tab”, “return”, “escape”, “space”, “delete”, “enter”, “insert”, “home”, “end”, “page up”, “page down”
- Function keys: “f1”, “f2”, “f3”, …
The names used to identify the keys are the same in the scripting interface and the Inspector.
Note also that the keys are accessible using the KeyCode enum parameter.
Источник
Ввод на мобильном устройстве
На мобильных устройствах класс Input предоставляет доступ к нажатию на экран, акселерометру и географическим/локационным данным.
Доступ к клавиатуре на мобильных устройствах обеспечивается через iOS keyboard.
Multi-Touch Screen
iPhone и iPod способны отслеживать до пяти нажатий на экран одновременно. Вы можете получить статус каждого нажатия на протяжении последнего кадра через массив Input.touches.
Android устройства не имеют определенного лимита на количество нажатий, которое можно отслеживать. Он колеблется от устройства к устройству и может варьироваться от одного-двух нажатий на старых устройствах, до пяти нажатий на некоторых новых.
Каждое нажатие пальцем представлено в структуре данных Input.Touch:
Свойство: | Функция: |
---|---|
fingerId | Уникальный индекс для нажатия. |
position | Позиция нажатия на экран. |
deltaPosition | Изменение позиции на экране с последнего кадра. |
deltaTime | Количество времени, которое прошло с тех пор как изменилось последнее состояние. |
tapCount | The iPhone/iPad screen is able to distinguish quick finger taps by the user. This counter will let you know how many times the user has tapped the screen without moving a finger to the sides. Android devices do not count number of taps, this field is always 1. |
phase | Describes so called “phase” or the state of the touch. It can help you determine if the touch just began, if user moved the finger or if they just lifted the finger. |
Фазы могут быть следующими:
Began | Палец только что прикоснулся к экрану. |
Moved | Палец передвинулся по экрану. |
Stationary | Палец прикоснулся к экрану, но с последнего кадра не двигался. |
Ended | Палец только что оторван от экрана. Это последняя фаза нажатий. |
Canceled | The system cancelled tracking for the touch, as when (for example) the user puts the device to their face or more than five touches happened simultaneously. This is the final phase of a touch. |
Ниже приведен пример скрипта, который выпускает луч там, где пользователь тапает по экрану:
Симуляция Мыши
On top of native touch support Unity iOS/Android provides a mouse simulation. You can use mouse functionality from the standard Input class. Note that iOS/Android devices are designed to support multiple finger touch. Using the mouse functionality will support just a single finger touch. Also, finger touch on mobile devices can move from one area to another with no movement between them. Mouse simulation on mobile devices will provide movement, so is very different compared to touch input. The recommendation is to use the mouse simulation during early development but to use touch input as soon as possible.
Акселерометр
При движении мобильных устройств, встроенный акселерометр сообщает линейное ускорение изменяется вдоль трех основных осей в трехмерном пространстве. Ускорение вдоль каждой оси сообщается непосредственно аппаратным обеспечением как значение G-Force. Значение 1,0 представляет собой нагрузку около +1г вдоль заданной оси, а величина –1,0 представляет –1g. Если вы держите устройство в вертикальном положении (с кнопкой “домой” внизу) перед собой, ось X (положительная) будет по правой стороне, ось Y (положительная) будет направлена вверх, а ось Z (положительная) будет указывать на вас.
Вы можете получить значение акселерометра, путем доступа к свойству Input.acceleration.
Приведенный ниже пример скрипта позволяет двигать объект, используя акселерометр:
Фильтр низких частот
Показания акселерометра могут быть отрывистыми и с шумом. Применив низкочастотную фильтрацию на сигнал, вы сгладите его и избавитесь от высокочастотного шума.
Приведенный ниже скрипт демонстрирует, как применить низкочастотную фильтрацию на показания акселерометра:
Чем больше значение LowPassKernelWidthInSeconds , тем медленнее фильтруется значение, которое будет приближаться к значению входного образца (и наоборот).
Я хочу получить как можно более точные показания акселерометра. Что я должен делать?
Чтение переменной Input.acceleration не означает дискретизацию. Проще говоря, Unity замеряет результат при частоте 60 Гц. и сохраняет его в переменную. На самом деле все немного сложнее — в случае значительной нагрузки на процессор, замеры акселерометра не происходят с постоянными временными интервалами. В результате, система может сделать два замера за один кадр, и один замер за следующий кадр.
Вы можете получить доступ ко всем замерам, выполненным акселерометром в текущем кадре. Следующий код иллюстрирует простое среднее всех событий акселерометра, которые были собраны в течение последнего кадра:
Источник