- Ввод на мобильном устройстве
- Multi-Touch Screen
- Симуляция Мыши
- Акселерометр
- Фильтр низких частот
- Я хочу получить как можно более точные показания акселерометра. Что я должен делать?
- 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?
- Unity input field android
- Input Field
- Properties
- Events
- Details
- Hints
Ввод на мобильном устройстве
На мобильных устройствах класс 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 Гц. и сохраняет его в переменную. На самом деле все немного сложнее — в случае значительной нагрузки на процессор, замеры акселерометра не происходят с постоянными временными интервалами. В результате, система может сделать два замера за один кадр, и один замер за следующий кадр.
Вы можете получить доступ ко всем замерам, выполненным акселерометром в текущем кадре. Следующий код иллюстрирует простое среднее всех событий акселерометра, которые были собраны в течение последнего кадра:
Источник
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:
Источник
Unity input field android
Unity Mobile Input Plugin for iOS and Android (Unity UI compatible) You can use default InputField UI component on iOS and Android without additional field above keyboard
Add url https://github.com/mopsicus/UnityMobileInput.git to Package Manager, or add the following line to Packages/manifest.json: «ru.mopsicus.mobileinput»: «https://github.com/mopsicus/UnityMobileInput.git»
- Native input field and keyboard on iOS and Android
- Hiding additional mobile input box (Android)
- Show «Done», «Clear» buttons (iOS)
- Return button type: Default, Next, Done, Search, Send
- Detect keyboard show/hide (with height)
- Custom fonts support
- Copy the files into your existing unity project asset folder
- Make empty Gameobject and attach Plugins to your new GameObject
- Attach MobileInputField script to your Unity UI InputField object
- For more options set ContentType to Custom to your InputField object
- For Android make sure your AndroidManifest.xml has the following setting
- To prevent screen slide up on Android when keyboard show, add this option to your AndroidManifest.xml
How to use custom fonts
- Copy font TTF to StreamingAssets folder
- Input font name in property instead «default»
- You are cool
Open Demo scene and build, to try how it works
Источник
Input Field
An Input Field is a way to make the text of a Text Control editable. Like the other interaction controls, it’s not a visible UI element in itself and must be combined with one or more visual UI elements in order to be visible.
An empty Input Field.
Text entered into the Input Field.
Properties
Property: | Function: | |
---|---|---|
Interactable | A boolean that determines if the Input Field can be interacted with or not. | |
Transition | Transitions are used to set how the input field transitions when Normal, Highlighted, Pressed or Disabled. | |
Navigation | Properties that determine the sequence of controls. See Navigation Options. | |
TextComponent | A reference to the Text element used as the contents of the Input Field | |
Text | Starting Value. The initial text placed in the field before editing begins. | |
Character Limit | The value of the maximum number of characters that can be entered into the input field. | |
Content Type | Define the type(s) of characters that your input field accepts | |
Standard | Any charcter can be entered. | |
Autocorrected | The autocorrection determines whether the input tracks unknown words and suggests a more suitable replacement candidate to the user, replacing the typed text automatically unless the user explicitly overrides the action. | |
Integer Number | Allow only whole numbers to be entered. | |
Decimal Number | Allow only numbers and a single decimal point to be entered. | |
Alphanumeric | Allow both letters and numbers. Symbols cannot be entered. | |
Name | Automatically capitalizes the first letter of each word. Note that the user can circumvent the capitalization rules using the Delete key. | |
Email Address | Allows you to enter an Alphanumeric string consisting of a maximum of one @ sign. periods/baseline dots cannot be entered next to each other. | |
Password* | Conceals the characters inputed with an asterisk. Allows symbols. | |
Pin | Conceals the characters inputed with an asterisk. Only allows only whole numbers to be entered. | |
Custom | Allows you to customise the Line Type, Input Type, Keyboard Type and Character Validation. | |
Line Type | Defines how test is formatted inside the text field. | |
Single Line | Only allows text to be on a single line. | |
Multi Line Submit | Allows text to use multiple lines. Only uses a new line when needed. | |
Multi Line Newline | Allows text to use multiple lines. User can use a newline by pressing the return key. | |
Placeholder | This is an optional ‘empty’ Graphic to show that the Input Field is empty of text. Note that this ‘empty’ graphic still displays even when the Input Field is selected (that is; when there is focus on it). eg; “Enter text…”. | |
Caret Blink Rate | Defines the blink rate for the mark placed on the line to indicate a proposed insertion of text. | |
Selection Color | The background color of the selected portion of text. | |
Hide Mobile Input (iOS only) | Hides the native input field attached to the onscreen keyboard on mobile devices. Note that this only works on iOS devices. |
Events
Property: | Function: |
---|---|
On Value Change | A UnityEvent that is invoked when the text content of the Input Field changes. The event can send the current text content as a string type dynamic argument. |
End Edit | A UnityEvent that is invoked when the user finishes editing the text content either by submitting or by clicking somewhere that removes the focus from the Input Field. The event can send the current text content as a string type dynamic argument. |
Details
The Input Field script can be added to any existing Text control object from the menu (Component > UI > Input Field). Having done this, you should also drag the object to the Input Field’s Text property to enable editing.
The Text property of the Text control itself will change as the user types and the value can be retrieved from a script after editing. Note that Rich Text is intentionally not supported for editable Text controls; the field will apply any Rich Text markup instantly when typed but the markup essentially “disappears” and there is no subsequent way to change or remove the styling.
Hints
- To obtains the text of the Input Field, use the text property on the InputField component itself, not the text property of the Text component that displays the text. The text property of the Text component may be cropped or may consist of asterisks for passwords.
Did you find this page useful? Please give it a rating:
Источник