2014年5月14日 星期三

【程式範例】觸控攝影機旋轉及縮放

複製程式碼貼到JavaScript,拖曳到攝影機上
再將目標物件拖曳到JavaScript上的target
var target: Transform;
var xSpeed: float = 20;
var ySpeed: float = 20;
var yMinLimit: float = -50;
var yMaxLimit: float = 50;
var distance: float = 7;
var pinchSpeed: float = -0.25;
var minDistance: float = 2;
var maxDistance: float = 30;
private var x: float = 0.0;
private var y: float = 0.0;
private var touch: Touch;
private var lastDist: float = 0;
private var curDist: float = 0;

function Start() {
    var angles: Vector3 = transform.eulerAngles;
    x = angles.y;
    y = angles.x;
}

function LateUpdate() {
    if (target) {
        if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved) {
            touch = Input.GetTouch(0);
            x += touch.deltaPosition.x * xSpeed * 0.02;
            y -= touch.deltaPosition.y * ySpeed * 0.02;
            y = Mathf.Clamp(y, yMinLimit, yMaxLimit);
            if (x < -360) x = 0;
            if (x > 360) x = 0;
        }
        if (Input.touchCount > 1 && (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved)) {
            var touch1 = Input.GetTouch(0);
            var touch2 = Input.GetTouch(1);
            curDist = Vector2.Distance(touch1.position, touch2.position);
            if (curDist > lastDist) {
                distance += Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition) * pinchSpeed / 10;
            }
            else {
                distance -= Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition) * pinchSpeed / 10;
            }
            lastDist = curDist;
        }
        distance = Mathf.Clamp(distance, minDistance, maxDistance);
        var rotation: Quaternion = Quaternion.Euler(y, x, 0.0f);
        var disVector: Vector3 = new Vector3(0.0f, 0.0f, -distance);
        var position: Vector3 = rotation * disVector + target.position;
        transform.rotation = rotation;
        transform.position = position;
    }
}

0 ♥:

張貼留言