Unity android касание экрана

Touch

struct in UnityEngine

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

Structure describing the status of a finger touching the screen.

Devices can track a number of different pieces of data about a touch on a touchscreen, including its phase (ie, whether it has just started, ended or moved), its position and whether the touch was a single contact or several taps. Furthermore, the continuity of a touch between frame updates can be detected by the device, so a consistent ID number can be reported across frames and used to determine how a particular finger is moving.

The Touch struct is used by Unity to store data relating to a single touch instance and is returned by the Input.GetTouch function. Fresh calls to GetTouch will be required on each frame update to obtain the latest touch information from the device but the fingerId property can be used to identify the same touch between frames.

Properties

altitudeAngle Value of 0 radians indicates that the stylus is parallel to the surface, pi/2 indicates that it is perpendicular.
azimuthAngle Value of 0 radians indicates that the stylus is pointed along the x-axis of the device.
deltaPosition The position delta since last change in pixel coordinates.
deltaTime Amount of time that has passed since the last recorded change in Touch values.
fingerId The unique index for the touch.
maximumPossiblePressure The maximum possible pressure value for a platform. If Input.touchPressureSupported returns false, the value of this property will always be 1.0f.
phase Describes the phase of the touch.
position The position of the touch in screen space pixel coordinates.
pressure The current amount of pressure being applied to a touch. 1.0f is considered to be the pressure of an average touch. If Input.touchPressureSupported returns false, the value of this property will always be 1.0f.
radius An estimated value of the radius of a touch. Add radiusVariance to get the maximum touch size, subtract it to get the minimum touch size.
radiusVariance This value determines the accuracy of the touch radius. Add this value to the radius to get the maximum touch size, subtract it to get the minimum touch size.
rawPosition The first position of the touch contact in screen space pixel coordinates.
tapCount Number of taps.
type A value that indicates whether a touch was of Direct, Indirect (or remote), or Stylus type.

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Читайте также:  Сбой шифрования андроид что делать планшет мегафон логин 3

Copyright ©2021 Unity Technologies. Publication Date: 2021-11-26.

Источник

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 Гц. и сохраняет его в переменную. На самом деле все немного сложнее — в случае значительной нагрузки на процессор, замеры акселерометра не происходят с постоянными временными интервалами. В результате, система может сделать два замера за один кадр, и один замер за следующий кадр.

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

Источник

DenTNT.trmw.ru

Записная книжка

Unity: Определить нажатие на объект

Если разрабатывать проект под Андроид, то приходится взаимодействовать с объектами сцены. В случае с элементами интерфейса (например UI Button) уже всё встроено и мы легко можем обработать событие нажатия на кнопку с помощью заполнения поля OnClick() в Инспекторе:

Однако для других объектов такого функционала нет. Придётся писать свои скрипты для отслеживания нажатия на экран устройства и определять, совпали ли эти координаты с координатами объекта.

1. Поместим на сцену объекты (у меня это цилиндр, куб и шар):

2. К каждому из этих объектов добавим скрипт ObjectAction.cs :

3. На камеру добавим скрипт SelectObject.cs :

Нам нужно определить, было ли хоть одно касание (тач), поэтому мы используем такое условие:

Поскольку мы находимся в цикле метода Update, то нас интересует момент самого первого срабатывания, а не все возможные. Для этого мы ограничиваем условие:

Далее создаётся «луч», который выходит из камеры и направлен на сцену в сторону координат прикосновения к экрану:

Если этот луч «попадает» в объект с коллайдером, то мы меняем цвет объекта:

После запуска приложения на смартфоне можно будет поменять цвет каждого объекта, просто нажав на него:

Источник

Ввод на мобильном устройстве

На мобильных устройствах класс 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 Гц. и сохраняет его в переменную. На самом деле все немного сложнее — в случае значительной нагрузки на процессор, замеры акселерометра не происходят с постоянными временными интервалами. В результате, система может сделать два замера за один кадр, и один замер за следующий кадр.

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

Источник

Читайте также:  Sleep talk recorder android
Оцените статью