Monday, September 21, 2015

zoom-in/out using two fingers mobile unity3d c sharp

iklan

About Testing :-

 * Attach below code to camera
 * connect your mobile through cable
 * make sure you should select unity remote device : Any Android Device at Editor setting
 * and Press Play 'Use your fingers to zoom in/out your screen'

About Coding :- 

 * You should store finger touches..
 * Store finger previous positions to Vector2
 * Find the magnitude... i mean current and previous delta positions
 * If the Camera projection is orthographic you should edit orthographicSize with some zoom constent 
 * If the Camera projection is Perspective you should edit fieldOfView with some zoom constent like script below
 * Happy Scripting


Code :-

using UnityEngine;
using System.Collections;


public class testZoom : MonoBehaviour
{
    public float perspectiveZoomSpeed = 0.5f;        
    public float orthoZoomSpeed = 0.5f;   
    
    
    void Update()
    {

        if (Input.touchCount == 2)
        {

            Touch touchZero = Input.GetTouch(0);
            Touch touchOne = Input.GetTouch(1);
            

            Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
            Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
            

            float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
            float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
            

            float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
            

            if (GetComponent<Camera>().orthographic)
            {
                GetComponent<Camera>().orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
                GetComponent<Camera>().orthographicSize = Mathf.Max(GetComponent<Camera>().orthographicSize0.1f);
            }
            else
            {
                GetComponent<Camera>().fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
                GetComponent<Camera>().fieldOfView = Mathf.Clamp(GetComponent<Camera>().fieldOfView0.1f179.9f);
            }
        }
    }
}




zoom-in/out using two fingers mobile unity3d c sharp
4/ 5
Oleh