【3D技术宅公社】XR数字艺术论坛  XR技术讨论 XR互动电影 定格动画

 找回密码
 立即注册

QQ登录

只需一步,快速开始

调查问卷
论坛即将给大家带来全新的技术服务,面向三围图形学、游戏、动画的全新服务论坛升级为UTF8版本后,中文用户名和用户密码中有中文的都无法登陆,请发邮件到324007255(at)QQ.com联系手动修改密码

3D技术论坛将以计算机图形学为核心,面向教育 推出国内的三维教育引擎该项目在持续研发当中,感谢大家的关注。

查看: 7339|回复: 0

Input输入控制

[复制链接]
发表于 2013-12-16 12:11:27 | 显示全部楼层 |阅读模式
The Input Manager is where you define all the different input axes and game actions for your project.
输入管理器可以设置项目的各种输入和操作。

The Input Manager 输入管理器
To see the Input Manager choose: Edit->Project Settings->Input.
输入管理器位于菜单的Edit->Project Settings->Input.
Properties 属性



  • Axes
    Contains all the defined input axes for the current project: Size is the number of different input axes in this project, Element 0, 1, ... are the particular axes to modify.
    设置当前项目中的所有输入轴:size为轴的数量。0,1…元素可以对每个轴进行修改。
  • Name 名称
    The string that refers to the axis in the game launcher and through scripting.
    轴的名称,用于游戏加载界面和脚本中。
  • Descriptive Name 描述
    A detailed definition of the Positive Button function that is displayed in the game launcher.
    游戏加载界面中,轴的正向按键的详细描述。
  • Descriptive Negative Name
    反向描述

    A detailed definition of the Negative Button function that is displayed in the game launcher.
    游戏加载界面中,轴的反向按键的详细描述。
  • Negative Button 反向按钮
    The button that will send a negative value to the axis.
    该按钮会给轴发送一个负值 。
  • Positive Button 正向按钮
    The button that will send a positive value to the axis.
    该按钮会给轴发送一个正值 。
  • Alt Negative Button 备选反向按钮
    The secondary button that will send a negative value to the axis.
    给轴发送负值的另一个按钮。
  • Alt Positive Button 备选正向按钮
    The secondary button that will send a positive value to the axis.
    给轴发送正值的另一个按钮。
  • Gravity 重力
    How fast will the input recenter. Only used when the Type is key / mouse button.
    输入复位的速度,仅用于类型为 键/鼠标 的按键。
  • Dead
    Any positive or negative values that are less than this number will register as zero. Useful for joysticks.
    任何小于该值的输入值(不论正负值)都会被视为0,用于摇杆。
  • Sensitivity
    灵敏度

    For keyboard input, a larger value will result in faster response time. A lower value will be more smooth. For Mouse delta the value will scale the actual mouse delta.
    对于键盘输入,该值越大则响应时间越快,该值越小则越平滑。对于鼠标输入,设置该值会对鼠标的实际移动距离按比例缩放。
  • Snap 对齐
    If enabled, the axis value will be immediately reset to zero after it receives opposite inputs. Only used when the Type is key / mouse button.
    如果启用该设置,当轴收到反向的输入信号时,轴的数值会立即置为0,仅用于键/鼠标 输入。
  • Invert 反转
    If enabled, the positive buttons will send negative values to the axis, and vice versa.
    启用该参数可以让正向按钮发送负值,反向按钮发送正值。
  • Type 类型
    Use Key / Mouse Button for any kind of buttons, Mouse Movement for mouse delta and scrollwheels, Joystick Axis for analog joystick axes and Window Movement for when the user shakes the window.
    所有的按钮输入都应设置为 键/鼠标 (Key / Mouse) 类型,对于鼠标移动和滚轮应设为 鼠标移动(Mouse Movement)。摇杆设为摇杆轴 (Joystick Axis),用户移动窗口设为窗口移动 (Window Movement)。
  • Axis
    Axis of input from the device (joystick, mouse, gamepad, etc.)
    设备的输入轴(摇杆,鼠标,手柄等)
  • Joy Num 摇杆编号
    Which joystick should be used. By default this is set to retrieve the input from all joysticks. This is only used for input axes and not buttons.
    设置使用哪个摇杆。默认是接收所有摇杆的输入。仅用于输入轴和非按键。
Details 细节
All the axes that you set up in the Input Manager serve two purposes:
在输入管理器中设置的轴有2个目的:



  • They allow you to reference your inputs by axis name in scripting
    让你可以在脚本中通过轴的名称来使用输入。
  • They allow the players of your game to customize the controls to their liking
    让游戏玩家可以自定义游戏的输入。
All defined axes will be presented to the player in the game launcher, where they will see its name, detailed description, and default buttons. From here, they will have the option to change any of the buttons defined in the axes. Therefore, it is best to write your scripts making use of axes instead of individual buttons, as the player may want to customize the buttons for your game.
在游戏加载界面中,玩家可以看到所有定义的轴,包括名称,详细说明,默认按键,他们可以通过选项改变轴的按键。因此,在脚本中你最好也使用轴而不是单独的按键,这样玩家就可以在你的游戏中自定义按键。

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
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:

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.

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.

value = Input.GetKey ("a");



Mobile Input
On iOS and Android, 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 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:


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 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.
Following is an example script which will shoot a ray whenever the user taps on the screen:
  1. var particle : GameObject;
  2. function Update () {
  3. for (var touch : Touch in Input.touches) {
  4. if (touch.phase == TouchPhase.Began) {
  5. // Construct a ray from the current touch coordinates
  6. var ray = Camera.main.ScreenPointToRay (touch.position);
  7. if (Physics.Raycast (ray)) {
  8. // Create a particle if hit
  9. Instantiate (particle, transform.position, transform.rotation);
  10. }
  11. }
  12. }
  13. }
复制代码
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.

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:
  1. var speed = 10.0;
  2. function Update () {
  3. var dir : Vector3 = Vector3.zero;

  4. // we assume that the device is held parallel to the ground
  5. // and the Home button is in the right hand

  6. // remap the device acceleration axis to game coordinates:
  7. // 1) XY plane of the device is mapped onto XZ plane
  8. // 2) rotated 90 degrees around Y axis
  9. dir.x = -Input.acceleration.y;
  10. dir.z = Input.acceleration.x;

  11. // clamp acceleration vector to the unit sphere
  12. if (dir.sqrMagnitude > 1)
  13. dir.Normalize();

  14. // Make it move 10 meters per second instead of 10 meters per frame...
  15. dir *= Time.deltaTime;

  16. // Move object
  17. transform.Translate (dir * speed);
  18. }
复制代码
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. var AccelerometerUpdateInterval : float = 1.0 / 60.0;
  2. var LowPassKernelWidthInSeconds : float = 1.0;

  3. private var LowPassFilterFactor : float = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds; // tweakable
  4. private var lowPassValue : Vector3 = Vector3.zero;
  5. function Start () {
  6. lowPassValue = Input.acceleration;
  7. }

  8. function LowPassFilterAccelerometer() : Vector3 {
  9. lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
  10. return lowPassValue;
  11. }
复制代码
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:
  1. var period : float = 0.0;
  2. var acc : Vector3 = Vector3.zero;
  3. for (var evnt : iPhoneAccelerationEvent in iPhoneInput.accelerationEvents) {
  4. acc += evnt.acceleration * evnt.deltaTime;
  5. period += evnt.deltaTime;
  6. }
  7. if (period > 0)
  8. acc *= 1.0/period;
  9. return acc;
复制代码
iOS Game Controller support

Starting with OS 7 standardized Game Controller Input API is provided by Apple. Unity support for this API comes as part of standard Unity Input API.

Detecting attached Game Controllers

Calling Input.GetJoystickNames() will enumerate attached controller names. Names follow this pattern: �[$profile_type,$connection_type] joystick $number by $model�. $profile_type might be either �basic� or �extended�, $connection_type is either �wired� or �wireless�. It could be used to detect the kind of connected controller. It�s worth re-checking this list every several seconds to detect if controllers have been attached/detached. Here�s an example how to do it in C#:

  1. private bool connected = false;
  2. IEnumerator CheckForControllers()
  3. {
  4. while(true)
  5. {
  6. var controllers = Input.GetJoystickNames();
  7. if (!connected && controllers.Length > 0)
  8. {
  9. connected = true;
  10. Debug.Log("Connected");
  11. }
  12. else if (connected && controllers.Length == 0)
  13. {
  14. connected = false;
  15. Debug.Log("Disconnected");
  16. }
  17. yield return new WaitForSeconds(1f);
  18. }
  19. }
  20. void Awake()
  21. {
  22. StartCoroutine(CheckForControllers());
  23. }
复制代码
When controllers are detected you can either hide on-screen touch controls or amend them to supplement controller input. The next task is to check for Game Controller input.


手机版|小黑屋|3D数字艺术论坛 ( 沪ICP备14023054号 )

GMT+8, 2024-11-23 22:27

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表