【Unity】7.5 移动设备输入

分类:Unity、C#、VS2015 spa

建立日期:2016-04-21 code

1、简介

在iOS和Android系统中,操做都是经过触摸来完成的。Input类中对触摸操做的方法或变量以下图所示: orm

image

经过GetTouch或者touches能够访问移动没备的触摸数据,数据保存在Touch的结构体中。下图是Touch的结构体变量:blog

image

2、基本用法示例

一、示例1(遍历全部Touch并输出Touch的信息) get

void OnGUI() string

{ it

//遍历全部Touch io

foreach(Touch touch in Input.touches) form

{ class

//输出Touch信息

GUILayout.Label(string.Format("手指:{0} 状态:{1} 位置:{2}",touch.fingerId,touch.phase.ToString(),touch.position));

}

}

二、示例2(Demo5_2_MobileExample.unity)

该例子演示如何打印当前触摸屏幕的手指数量。

下面是MobileExample.cs文件中的代码:

using UnityEngine;
using System.Collections;
public class MobileExample : MonoBehaviour
{
    //定义手指在触摸屏上的数量
    public int fingerCount = 0;

    void Update()
    {
        foreach (var touch in Input.touches)
        {
            if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
                fingerCount++;
        }
        if (fingerCount > 0)
            print("用户有 " + fingerCount + " 手指触摸了屏幕");

    }

    void OnGUI()
    {
        //输出手指在触摸屏上的数量至界面中
        GUILayout.Label("手指数量:" + fingerCount);
    }
}

运行预览效果:

image

三、示例3(Demo5_3_MobileMoveExample.unity)

该例子演示如何根据手指在屏幕上的滑动来移动物体。

MobileMoveExample.cs文件的代码以下:

using UnityEngine;
using System.Collections;

public class MobileMoveExample : MonoBehaviour
{
    public float speed = 0.1f;
    void Update()
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            // 获得手指在这一帧的移动距离
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
            // 在XY平面上移动物体
            transform.Translate(-touchDeltaPosition.x * speed, -touchDeltaPosition.y * speed, 0);
        }
    }
}

运行预览效果和示例2的截图相同。

相关文章
相关标签/搜索