全面解析 Unity 的输入输出以及 移动设置相关

Desktop

Note: Keyboard, joystick and gamepad input works only on the desktop version of Unity.

注意:键盘,操纵杆和游戏手柄输入仅工作于Unity桌面版本。

Unity supports keyboard, joystick and gamepad input.

Unity支持,键盘,操纵杆和游戏手柄输入。

Virtual axes and buttons can be created in the Input Manager, and end users can configure Keyboard input in a nice screen configuration dialog.

在输入管理器可以创建虚拟轴和按钮,并终端用户可以在屏幕配置对话框配置键盘输入。

You can setup joysticks, gamepads, keyboard, and mouse, then access them all through one simple scripting interface.

用户可以设置操纵杆,游戏手柄,键盘和鼠标,然后可以通过简单的脚本接口访问它们。

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. 
    水平和垂直被映射到w, a, s, d键和方向键
  • Fire1, Fire2, Fire3 are mapped to Control, Option (Alt), and Command, respectively. 
    Fire1, Fire2, Fire3被分别映射到Ctrl,Option(Alt)和Command键
  • Mouse X and Mouse Y are mapped to the delta of mouse movement. 
    Mouse X 和 Mouse Y被映射到鼠标移动增量
  • Window Shake X and Window Shake Y is mapped to the movement of the window. 
    Window Shake X 和 Window Shake Y 被映射到窗口的移动

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.

如果想添加新的虚拟轴,选择菜单Edit->Project Settings->Input menu。这里可以改变每个轴的设置。

You map each axis to two buttons on a joystick, mouse, or keyboard keys.

  • 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 
    Alt负按钮
    Alternative button used to push the axis in the negative direction.
    Alt按钮用于在负方向移动轴
  • Alt Positive Button 
    Alt正按钮
    Alternative button used to push the axis in the positive direction.
    Alt按钮用于在正方向移动轴
  • Gravity  重力
    Speed in units per second that the axis falls toward neutral when no buttons are pressed.
    当没有按钮被按下,在单位每秒速度,轴下降到0。
  • Dead  死亡
    Size of the analog dead zone. All analog device values within this range result map to neutral.
    模拟的死区大小。 设定范围内所有模拟设备的值为0。
  • 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.
    如果启用,当按下相反方向的按钮,该轴值将重设为0。
  • 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:

从像这样的脚本,可以查询当前状态:

value = Input.GetAxis ("Horizontal");

An axis has a value between -1 and 1. The neutral position is 0. This is the case for joystick input and keyboard input.

一个轴具有-1和1之间的值。中间位置为0。这种情况用于操纵杆输入和键盘输入。

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.

然而,鼠标增量和Window Shake增量是鼠标或窗口从上一帧到现在的移动。这意思是当用户快速移动鼠标时,它可能大于1或小于-1。

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 button 0", "joystick button 1", "joystick 1 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.

在脚本和检视面板,用来识别键的名称是一样的。

value = Input.GetKey ("a");

Mobile Input 移动设备输入

Unity iOS/Android offers you access to the iPhone, iPad and Android input systems via Input and iOS Input scripting interfaces.

Unity iOS/Android 为你提供访问iphone,iPad和Android的输入系统,通过Input 和 iOS Input脚本接口。

Input provides access to the multi-touch screen, accelerometer and device orientation. iOS Input provides access to geographical location.

Input提供访问多点触控屏幕,加速度和设备方向。iOS Input提供访问地理位置。

Access to keyboard on mobile devices is provided via the iOS keyboard.

访问键盘是通过iOS keyboard。

Multi-Touch Screen 多点触控屏幕

The iPhone 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.

iPhone和iPod触控设备是具有五个手指触控屏幕同时跟踪能力。通过访问Input.touches属性数值,可以取回每个手指触摸屏幕在最后一帧的状态。

Android

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.

Android设备,能跟踪多少个手指没有统一的限制。相反,在不同的设备上可能是不同的,从老设备的两指触控,到新设备的五指触控。

Each finger touch is represented by an Input.Touch data structure:

每个手指触控是通过Input.touches数据结构描述的:

  • 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.
    iPhone/iPad屏幕能够识别用过的快速点击, 这个计数器让你知道用户点击屏幕多少次,而不是移动手指。android设备不对点击计数,这个方法总是返回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 he just lifted the finger.
    描述触摸的状态,可以帮助开发者确定用户是否刚开始触摸,是否用户移动手指,是否用户刚刚抬起手指。

Phase can be one of the following:

相位(状态)可能是下列之一:

  • 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 her face or more than five touches happened simultaneously. This is the final phase of a touch.
    系统取消了触控跟踪,如,用户将设备放在了脸上或超过同时超过5个触摸点。这是触控的最后状态。

Following is an example script which will shoot a ray whenever the user taps on the screen:

下面的例子,只要用户在屏幕上点击,将射出一条光线:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var particle : GameObject;
function Update () {
     for ( var touch : Touch in Input.touches) {
         if (touch.phase == TouchPhase.Began) {
             // Construct a ray from the current touch coordinates
             //从当前的触摸坐标建一条光线
             var ray = Camera.main.ScreenPointToRay (touch.position);
             if (Physics.Raycast (ray)) {
                 // Create a particle if hit
                 //如果触摸就创建一个例子
                 Instantiate (particle, transform.position, transform.rotation);
             }
         }
     }
}

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.

除了原有的触控之外,Unity iOS/Android还提供了鼠标模拟。从标准的Input类中,可以使用鼠标功能。

Device Orientation 设备方向

Unity iOS/Android allows you to get discrete description of the device physical orientation in three-dimensional space. Detecting a change in orientation can be useful if you want to create game behaviors depending on how the user is holding the device.

Unity iOS/Android 可以获取设备在现实三维空间的物理方向。检测方向改变用于, 如果你想根据用户怎样手持设备来创建游戏行为。

You can retrieve device orientation by accessing the Input.deviceOrientation property. Orientation can be one of the following:

通过访问Input.deviceOrientation属性,能检索设备的方向。方向值可能是下列之一:

  • Unknown  未知
    The orientation of the device cannot be determined. For example when device is rotate diagonally.
    不能确定设备的方向,例如,当设备正好旋转为对角时。
  • Portrait  纵向
    The device is in portrait mode, with the device held upright and the home button at the bottom.
    设备在纵向模式,设备在直立状态,home按钮在底部
  • PortraitUpsideDown  纵向倒置
    The device is in portrait mode but upside down, with the device held upright and the home button at the top.
    设备在纵向模式,但为倒置,设备在直立状态,home按钮在顶部
  • LandscapeLeft  左横向
    The device is in landscape mode, with the device held upright and the home button on the right side.
    设备为横向模式,设备为直立状态,并home按钮在右边
  • LandscapeRight  右横向
    The device is in landscape mode, with the device held upright and the home button on the left side.
    设备为横向模式,设备为直立状态,并home按钮在左边
  • FaceUp  面向上
    The device is held parallel to the ground with the screen facing upwards.
    设备与地面平行,并屏幕面朝上
  • FaceDown  面向下
    The device is held parallel to the ground with the screen facing downwards.
    设备与地面平行,并屏幕面朝下

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.

在手机设备移动时,内置加速度传感器报告在三维空间,沿着三个主要轴上的线性加速度改变。沿着每个轴的加速度由硬件作为G-force值直接报告。值为1表示沿给定轴增加1g负载,值为-1.0表示减少1g。如果用户在面前竖直拿着设备(home按钮在底部),X轴指向右,Y轴指向上,Z轴指向前。

You can retrieve the accelerometer value by accessing the Input.acceleration property.

可以通过访问Input.acceleration属性,取回加速度传感器的值。

The following is an example script which will move an object using the accelerometer:

下面的例子,将使用加速度传感器移动一个物体:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var speed = 10.0;
function Update () {
     var dir : Vector3 = Vector3.zero;
 
     // we assume that the device is held parallel to the ground
     // and the Home button is in the right hand
     //假设该设备与地面平行,Home按钮在右边
     // remap the device acceleration axis to game coordinates:
     //重新映射设备加速度轴到游戏坐标:
     //  1) XY plane of the device is mapped onto XZ plane
     //      设备的XY平面映射到XZ平面
     //  2) rotated 90 degrees around Y axis
     //      沿着Y轴旋转90度
     dir.x = -Input.acceleration.y;
     dir.z = Input.acceleration.x;
 
     // clamp acceleration vector to the unit sphere
     //钳制加速度向量到单位球
     if (dir.sqrMagnitude > 1)
         dir.Normalize();
 
     // Make it move 10 meters per second instead of 10 meters per frame...
     //使它每秒移动10米,而不是每帧10米
     dir *= Time.deltaTime;
 
     // Move object 移动物体
     transform.Translate (dir * speed);
}

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:

下面的例子显示,怎样应用低通到加速度传感器数值:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
var AccelerometerUpdateInterval : float = 1.0 / 60.0;
var LowPassKernelWidthInSeconds : float = 1.0;
 
private var LowPassFilterFactor : float = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds; // tweakable
private var lowPassValue : Vector3 = Vector3.zero;
function Start () {
     lowPassValue = Input.acceleration;
}
 
function LowPassFilterAccelerometer() : Vector3 {
     lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
     return lowPassValue;
}

The greater the value of LowPassKernelWidthInSeconds, the slower the filtered value will converge towards the current input sample (and vice versa). You should be able to use the LowPassFilter() function instead of avgSamples().

LowPassKernelWidthInSeconds的值越大, 被过滤值将汇集当前输入采样越慢,反之亦然。应该使用LowPassFilter()函数,而不是avgSamples()。

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.

读取 Input.acceleration变量,不等于从硬件采样。简而言之,Unity硬件样品频率为60Hz并储存结果到变量。在现实中,是一个有点复杂的东西--加速度传感器采样不会发生在一致的时间间隔,如果大量的CPU负荷的情况下,因此,系统可能会报告一帧中的2个采样,那么1个采样在下一帧。

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:

通过加速度传感器在帧间可以访问所有测量。

?
1
2
3
4
5
6
7
8
9
var period : float = 0.0;
var acc : Vector3 = Vector3.zero;
for ( var evnt : iPhoneAccelerationEvent  in iPhoneInput.accelerationEvents) {
     acc += evnt.acceleration * evnt.deltaTime;
     period += evnt.deltaTime;
}
if (period > 0)
     acc *= 1.0/period;
return acc;

Further Reading 深入阅读

The Unity mobile input API is originally based on Apple's API. It may help to learn more about the native API to better understand Unity's Input API. You can find the Apple input API documentation here:

Unity移动Input API本来是基于Apple's API。这可以帮助你学习更多关于原生API,更好的理解Untiy的Input API。在这里找到Apple的 Input API文档:

  • Programming Guide: Event Handling (Apple iPhone SDK documentation)
  • UITouch Class Reference (Apple iOS SDK documentation)

Note: The above links reference your locally installed iPhone SDK Reference Documentation and will contain native ObjectiveC code. It is not necessary to understand these documents for using Unity on mobile devices, but may be helpful to some!

注意:上面的链接参考你本地安装的iPHone SDK参考文档,也将包含ObjectiveC代码。对于在移动设备使用Unity开发,没有必要理解这些文档,但是可能或许有些一下帮助。

iOS

Device geographical location 设备地理位置

Device geographical location can be obtained via the iPhoneInput.lastLocation property. Before calling this property you should start location service updates using iPhoneSettings.StartLocationServiceUpdates() and check the service status viaiPhoneSettings.locationServiceStatus. See the scripting reference for details.

设备地理位置可以通过iPhoneInput.lastLocation属性获得。在调用此属性之前,应该使用iPhoneSettings.StartLocationServiceUpdates()先开始位置服务的更新并通过iPhoneSettings.locationServiceStatus检查服务器状态。

参见脚本更多细节。

你可能感兴趣的:(最新学习)