Skip to content

Instantly share code, notes, and snippets.

@aVolpe
Created March 31, 2014 20:46
Show Gist options
  • Save aVolpe/9901849 to your computer and use it in GitHub Desktop.
Save aVolpe/9901849 to your computer and use it in GitHub Desktop.
A simple script that manipulates the camera through TouchScript to move it around a object. (Can zoom and rotate too).
using System;
using TouchScript.Events;
using TouchScript.Gestures;
using TouchScript.Gestures.Simple;
using UnityEngine;
public class CameraGestures : MonoBehaviour {
public float Speed = 10f;
public float PanSpeed = 15f;
public float ScaleSpeed = 1.5f;
public float RotateSpeed = 1.5f;
public float MaxDistance = 30f;
public float MinDistance = 5f;
public bool Enabled = true;
public Transform Focus;
private void Start()
{
if (GetComponent<SimplePanGesture>() != null)
{
GetComponent<SimplePanGesture>().StateChanged += onPanStateChanged;
}
if (GetComponent<SimpleScaleGesture>() != null)
{
GetComponent<SimpleScaleGesture>().StateChanged += onScaleStateChanged;
}
if (GetComponent<SimpleRotateGesture>() != null)
{
GetComponent<SimpleRotateGesture>().StateChanged += onRotateStateChanged;
}
}
private void onPanStateChanged(object sender, GestureStateChangeEventArgs e)
{
if (!Enabled) {
return;
}
switch (e.State)
{
case Gesture.GestureState.Began:
case Gesture.GestureState.Changed:
var gesture = (SimplePanGesture)sender;
/**
* Si hay mas de un dedo en la pantalla, no se rota.
*/
if (gesture.ActiveTouches.Count != 1) {
return;
}
if (gesture.LocalDeltaPosition != Vector3.zero)
{
/**
* Velocidad con la que rotará
* */
var fraction = Speed * Time.deltaTime;
/**
* Cuanto se debería mover?
*
* Se define como:
* La cantidad que se movio el mouse desde la última llamada por la velocidad por la velocidad del PanSpeed.
*
* Es decir, si yo muevo mi dedo un poquito hacia arriba, esto debería ser un poquito hacia arriba.
*
* El menos al comienzo hace que el movimiento sea inverso.
* */
Vector3 movement = - gesture.LocalDeltaPosition * Speed * PanSpeed;
/**
* A donde debería ir?
*
* Es la posición actual de la camara más lo que se debería mover.
*
* El problema de este calculo es que, al sumarle un vector a la posición de la camara, la distancia con el "Foco"
* aumenta, es decir:
* Teniendo:
* float distanciaPrevia = magnitudDe(camara.position - focus.position);
* float distanciaNueva = magnitudDe(goTo - focus.position);
*
* *Siempre*:
* distanciaPrevia < distanciaNueva
*
* Esto se debe a que aumentamos el vector.
*
*
* */
Vector3 goTo = (GetCamera().transform.position + movement * fraction);
/**
* Para solucionar el problema de "goTo" creamos una variable de movimiento ideal.
*
* Primero hallamos el vector distancia que existe entre el Foco y a donde queremos ir, el cual es un vector de
* longitud mayor al a deseada, por eso lo normalizamos y multiplicamos por la distancia original, preservando así
* la distancia.
*
* Luego sumamos ese vector resultado a la posición de nuestro foco.
* */
Vector3 ideal = Focus.position + (goTo - Focus.position).normalized * GetDistanceFromFocus();
if (ideal.y < 1) {
ideal.y = 1;
}
GetCamera().transform.position = ideal;
/*
* Miramos al objeto para que no perderlo de foco.
*/
transform.LookAt(Focus.transform);
}
break;
}
}
private void onRotateStateChanged(object sender, GestureStateChangeEventArgs e)
{
if (!Enabled) {
return;
}
switch (e.State)
{
case Gesture.GestureState.Began:
case Gesture.GestureState.Changed:
var gesture = (SimpleRotateGesture)sender;
if (Math.Abs(gesture.LocalDeltaRotation) > 0.01)
{
float speed = Speed * Time.deltaTime * RotateSpeed;
Quaternion localRotationToGo = transform.localRotation;
if (transform.parent == null)
{
localRotationToGo = Quaternion.AngleAxis(gesture.LocalDeltaRotation, gesture.WorldTransformPlane.normal) * localRotationToGo;
} else
{
localRotationToGo = Quaternion.AngleAxis(gesture.LocalDeltaRotation, transform.parent.InverseTransformDirection(gesture.WorldTransformPlane.normal)) * localRotationToGo;
}
transform.localRotation = Quaternion.Lerp(transform.localRotation, localRotationToGo, speed);
}
break;
}
}
private void onScaleStateChanged(object sender, GestureStateChangeEventArgs e)
{
if (!Enabled) {
return;
}
switch (e.State)
{
case Gesture.GestureState.Began:
case Gesture.GestureState.Changed:
var gesture = (SimpleScaleGesture)sender;
if (Math.Abs(gesture.LocalDeltaScale - 1) > 0.00001)
{
/**
* La velocidad se define por la diferencia de posición de las posiciones de los dedos
* por la velocidad por la velocidad de escalado.
*
* speed es negativo si delta es menor a 1, es decir, si los dedos se estan acercando.
*/
float speed = (gesture.LocalDeltaScale - 1) * Speed * ScaleSpeed;
/**
* Se obtiene la distancia actual de la camara al objeto
*/
Vector3 distance = GetCamera().transform.position - Focus.transform.position;
/**
* Se normaliza la distancia, se la multiplica por la velicidad y se la resta de la distancia
* original, para obtener una nueva distancia.
*/
distance -= Vector3.Normalize(distance) * speed;
if (distance.magnitude > MaxDistance) {
distance = Vector3.Normalize(distance) * MaxDistance;
}
if (distance.magnitude < MinDistance) {
distance = Vector3.Normalize(distance) * MinDistance;
}
/**
* Se mueve la camara a la posición real.
*/
GetCamera().transform.position = Focus.transform.position + distance;
}
break;
}
}
/**
* Retorna la distancia al foco actual.
*/
private float GetDistanceFromFocus() {
return GetDistanceFromFocus(transform.position);
}
private float GetDistanceFromFocus(Vector3 point) {
return (Focus.transform.position - point).magnitude;
}
private void Log(object toLog) {
Debug.Log(toLog);
}
private Camera GetCamera() {
return Camera.main;
}
}
@zgmax
Copy link

zgmax commented Feb 11, 2015

wow thanks man,

I'm getting error
" Error CS0234: The type or namespace name 'Events' does not exist in the namespace 'TouchScript' (are you missing an assembly reference?) (CS0234) (Assembly-CSharp)"

Can you help please

Thanks

Max

@ManojBalaji3001
Copy link

can you please tell me how to turn on and off flashlight on unity 3d android device

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment