2013年6月21日金曜日

【Unity】タッチ操作で特定のオブジェクトを中心にカメラを回す

タッチでグリグリしたい。その2 (その1はこちら)
特定のオブジェクトを中心にカメラを旋回させたい。

↓こんな感じ。
  • 左右に指を動かすとカメラが左右に旋回
  • 上下に指を動かすとカメラが上下に移動

方法

カメラと親子関係になるオブジェクトを用意することで実現できました。

まずはオブジェクトを準備
  • CameraAxis(空のGameObject)
    座標(0,5,0)
  • カメラをCameraAxisの子供に設定
    座標(0,5,-20)
  • 適当なCube
    カメラの旋回が分かりやすいように置いただけ
こんな感じ
CameraAxisスクリプトの追加
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class CameraAxis : MonoBehaviour
{
    public float RotateSpeed = 0.1f;
    public float UpDownSpeed = 0.01f;

    void Update()
    {
        int touchCount = Input.touches
             .Count(t => t.phase != TouchPhase.Ended && t.phase != TouchPhase.Canceled);
        if (touchCount == 1)
        {
            Touch t = Input.touches.First();
            switch (t.phase)
            {
                case TouchPhase.Moved:

                    //移動量
                    float xDelta = t.deltaPosition.x * RotateSpeed;
                    float yDelta = t.deltaPosition.y * UpDownSpeed;

                    //左右回転
                    this.transform.Rotate(0, xDelta, 0, Space.World);
                    //上下移動
                    this.transform.position += new Vector3(0, -yDelta, 0);

                    break;
            }
        }
    }
}
スクリプト説明…は要らないかな
カメラの親となるCameraAxisオブジェクトを回転・上下移動するだけです。

スクリプトの適用

  • CameraAxisオブジェクトにCameraAxisスクリプトを適用
ドラッグ&ドロップ

実行

見まわせるようになった
いい感じー。




スポンサーリンク

Related Posts Plugin for WordPress, Blogger...