Hello Guys-
I am in desperate need of your help. I am new to unity and C# and I am trying to finish a code that will allow users to pan the camera along the z,y axis on touchscreen devices. It is in 3D , but more like a camera above RTS game. Feel free guys to use it in your projects! This is a working script that will pan left and right (on the X axis) and has public variables for restricting how far they can go on the x-axis, so the user is not panning into infinity. It also has a working 2 finger zoom script with min,max variables as well. Be easy on me, I am a noob. This is what I have so far.
using UnityEngine;
using System.Collections;
public class CameraTest : MonoBehaviour {
public float moveSensitivityX = 0.1f;
public float moveSensitivityZ = 0.1f;
public bool updateZoomSensitivity = true;
public float orthoZoomSpeed = 0.05f;
public float minZoom = 1.0f;
public float maxZoom = 20.0f;
public bool invertMoveX = false;
public bool invertMoveZ = false;
public float minX = -3f;
public float maxX = 3f;
private Camera _camera;
// Use this for initialization
void Start () {
_camera = GetComponent<Camera>();
}
// Update is called once per frame
void Update () {
if (updateZoomSensitivity) {
moveSensitivityX = _camera.fieldOfView / 5.0f;
moveSensitivityZ = _camera.fieldOfView / 5.0f;
}
Touch[] touches = Input.touches;
if (touches.Length > 0) {
// Single touch move
if (touches.Length == 1) {
if (touches [0].phase == TouchPhase.Moved) {
Vector3 delta = touches [0].deltaPosition;
float positionX = delta.x * moveSensitivityX * Time.deltaTime;
positionX = invertMoveX ? positionX : positionX * -1;
float positionZ = delta.z * moveSensitivityZ * Time.deltaTime;
positionZ = invertMoveZ ? positionZ : positionZ;
_camera.transform.position += new Vector3 (positionX, 0, positionZ);
_camera.transform.position = new Vector3(Mathf.Clamp(transform.position.x, minX, maxX),transform.position.y, transform.position.z);
}
}
}
// Double Touch Zoom
if (touches.Length == 2) {
Touch touchOne = touches[0];
Touch touchTwo = touches[1];
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
Vector2 touchTwoPrevPos = touchTwo.position - touchTwo.deltaPosition;
float prevTouchDeltaMag = (touchOnePrevPos - touchTwoPrevPos).magnitude;
float touchDeltaMag = (touchOne.position - touchTwo.position).magnitude;
float deltaMagDiff = prevTouchDeltaMag - touchDeltaMag;
_camera.fieldOfView += deltaMagDiff * orthoZoomSpeed;
_camera.fieldOfView = Mathf.Clamp(_camera.fieldOfView,minZoom,maxZoom);
}
}
}