Version: 2023.1
public static Touch GetTouch (int index);

参数

index 设备屏幕上的触摸输入。

返回

Touch 结构中的触摸详细信息。

描述

调用 Input.GetTouch 以获取 Touch 结构。

Input.GetTouch 为所选的屏幕触摸操作(例如来自手指或触笔)返回 TouchTouch 描述触摸屏。index 参数选择屏幕触摸操作。

Input.touchCount 提供当前屏幕触摸操作的次数。如果 Input.touchCount 大于零,GetTouch index 设置要检查哪些屏幕触摸操作。Touch 返回包含屏幕触摸操作详细信息的 /struct/。每次触摸屏幕,都会使 Input.touchCount 增大。

GetTouch 返回 Touch 结构。可以用零来获得首次屏幕触摸。例如,Touch 包含 position(单位为像素)。

未分配临时变量。

using UnityEngine;
using System.Collections;
using UnityEngine.iOS;

// Input.GetTouch example. // // Attach to an origin based cube. // A screen touch moves the cube on an iPhone or iPad. // A second screen touch reduces the cube size.

public class ExampleClass : MonoBehaviour { private Vector3 position; private float width; private float height;

void Awake() { width = (float)Screen.width / 2.0f; height = (float)Screen.height / 2.0f;

// Position used for the cube. position = new Vector3(0.0f, 0.0f, 0.0f); }

void OnGUI() { // Compute a fontSize based on the size of the screen width. GUI.skin.label.fontSize = (int)(Screen.width / 25.0f);

GUI.Label(new Rect(20, 20, width, height * 0.25f), "x = " + position.x.ToString("f2") + ", y = " + position.y.ToString("f2")); }

void Update() { // Handle screen touches. if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0);

// Move the cube if the screen has the finger moving. if (touch.phase == TouchPhase.Moved) { Vector2 pos = touch.position; pos.x = (pos.x - width) / width; pos.y = (pos.y - height) / height; position = new Vector3(-pos.x, pos.y, 0.0f);

// Position the cube. transform.position = position; }

if (Input.touchCount == 2) { touch = Input.GetTouch(1);

if (touch.phase == TouchPhase.Began) { // Halve the size of the cube. transform.localScale = new Vector3(0.75f, 0.75f, 0.75f); }

if (touch.phase == TouchPhase.Ended) { // Restore the regular size of the cube. transform.localScale = new Vector3(1.0f, 1.0f, 1.0f); } } } } }

第二个示例:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { public GameObject projectile; public GameObject clone;

void Update() { for (int i = 0; i < Input.touchCount; ++i) { if (Input.GetTouch(i).phase == TouchPhase.Began) { clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject; } } } }

第三个示例:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { public GameObject particle; void Update() { for (int i = 0; i < Input.touchCount; ++i) { if (Input.GetTouch(i).phase == TouchPhase.Began) { // Construct a ray from the current touch coordinates Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);

// Create a particle if hit if (Physics.Raycast(ray)) { Instantiate(particle, transform.position, transform.rotation); } } } } }