Unity之触屏控制_实现模型旋转和缩放—Touch类的使用

来源:互联网 发布:java记录日志的方式 编辑:程序博客网 时间:2024/06/01 07:45

      如果我们在Unity中实现物体的放大和旋转等需要触屏控制的功能,可以使用类Touch,可以理解为屏幕触点。

     首先让我们看一看API中的定义:Structure describing the status of a finger touching the screen,大体意思是,描述手指接触屏幕状态的结构体。

    它的主要变量有:

        Touch.phase:Describes the phase of the touch.,即描述触摸的阶段(阶段主要分分为三种:Began(手指刚接触屏幕),move(手指在屏幕上移动),end(手指离开屏幕))。

        Touch.position:当前触点的位置,返回的是一个二维向量。

        注1:了解当前屏幕触点数目可以雕用:Input.TouchCount.

        注2:获得屏幕的触点可以调用:Input.getTouch(int index);index为接触屏幕的触点编号(从0开始计)

        现在让我们实现物体的放大和旋转功能:

      

using UnityEngine;
using System.Collections;

public class rotateand_scale : MonoBehaviour {
    private Vector2 oldPo1;
    private Vector2 oldPo2;
    private Vector2 newPo1;
    private Vector2 newPo2;
    private Touch touch1;
    private Touch touch2;
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
        //单点触碰旋转
     if(Input.touchCount==1)
        {
            touch1 = Input.GetTouch(0);
            Vector2 slip = touch1.deltaPosition;
            this.transform.Rotate(new Vector3(slip.y, slip.x),Space.World);
        }else if(Input.touchCount==2) //多点触碰放大或缩小
        {
            touch1 = Input.GetTouch(0);
            touch2 = Input.GetTouch(1);
            //记录两个手指都触屏时的位置
            if(touch1.phase == TouchPhase.Began||touch2.phase==TouchPhase.Began)
            {
                oldPo1 = touch1.position;
                oldPo2 = touch2.position;
            }
            //随手指的移动变换物体的大小
            if(touch1.phase==TouchPhase.Moved&&touch2.phase==TouchPhase.Moved)
            {
                newPo1 = touch1.position;
                newPo2 = touch2.position;
                float distance1 = Vector2.Distance(oldPo1, oldPo2);
                float distance2 = Vector2.Distance(newPo1, newPo2);
                float scale = distance2 / distance1;
                if(scale<0.3)
                {
                    scale = 0.3f;
                } else if(scale>2)
                {
                    scale = 2.0f;
                }
                this.transform.localScale *= scale;
            }

        }
 }
}
注:space类 操作的空间,官方:The coordinate space in which to operate.
       space.Word : Applies transformation relative to the world coordinate system.指游戏里面的空间系统
       space.self: : Applies transformation relative to the local coordinate system. 本地的空间系统。


0 0