- 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?
- Mobile device input
- Multi-touch screen
- Mouse simulation
- Акселерометр
- Фильтр низких частот
- Я хочу получить как можно более точные показания акселерометра. Что я должен делать?
- Input Manager
- Virtual axes
- Adding, removing, and copying virtual axes
- Mapping virtual axes to controls
- Using virtual axes in scripts
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:
Источник
Mobile device input
On mobile devices, the Input class offers access to touchscreen, accelerometer and geographical/location input.
Доступ к клавиатуре на мобильных устройствах обеспечивается через 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 устройства не имеют определенного лимита на количество нажатий, которое можно отслеживать. Он колеблется от устройства к устройству и может варьироваться от одного-двух нажатий на старых устройствах, до пяти нажатий на некоторых новых.
Каждое нажатие пальцем представлено в структуре данных Input.Touch:
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/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.
Акселерометр
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.
Вы можете получить значение акселерометра, путем доступа к свойству Input.acceleration.
Приведенный ниже пример скрипта позволяет двигать объект, используя акселерометр:
Фильтр низких частот
Показания акселерометра могут быть отрывистыми и с шумом. Применив низкочастотную фильтрацию на сигнал, вы сгладите его и избавитесь от высокочастотного шума.
Приведенный ниже скрипт демонстрирует, как применить низкочастотную фильтрацию на показания акселерометра:
Чем больше значение LowPassKernelWidthInSeconds , тем медленнее фильтруется значение, которое будет приближаться к значению входного образца (и наоборот).
Я хочу получить как можно более точные показания акселерометра. Что я должен делать?
Чтение переменной Input.acceleration не означает дискретизацию. Проще говоря, Unity замеряет результат при частоте 60 Гц. и сохраняет его в переменную. На самом деле все немного сложнее — в случае значительной нагрузки на процессор, замеры акселерометра не происходят с постоянными временными интервалами. В результате, система может сделать два замера за один кадр, и один замер за следующий кадр.
Вы можете получить доступ ко всем замерам, выполненным акселерометром в текущем кадре. Следующий код иллюстрирует простое среднее всех событий акселерометра, которые были собраны в течение последнего кадра:
Источник
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 the Input category.
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:
Свойство: | Функция: |
---|---|
Name | Axis name. You can use this to access the axis from scripts. |
Descriptive Name, Descriptive Negative Name | These values are deprecated and do not work. Previously, they displayed for the user on the Rebind Controls screen at startup, but this screen has also been deprecated. |
Negative Button, Positive Button | The controls to push the axis in the negative and positive direction respectively. These can be keys on a keyboard, or buttons on a joystick or mouse. |
Alt Negative Button, Alt Positive Button | Alternative controls to push the axis in the negative and positive direction respectively. |
Gravity | Speed in units per second that the axis falls toward neutral when no input is present. |
Dead | How far the user needs to move an analog stick before your application registers the movement. At runtime, input from all analog devices that falls within this range will be considered null. |
Sensitivity | Speed in units per second that 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 that corresponds to the opposite direction. |
Type | The type of input that controls the axis. Select from these values: — Key or Mouse button |
Axis | The axis of a connected device that controls this axis. |
JoyNum | The connected Joystick that controls this axis. You can select a specific joystick, or query input from all joysticks. |
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.
Источник