25
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Unity]マウスによる球体座標のカメラ移動

Last updated at Posted at 2015-11-24
  • モデル見たり、TPSなゲームを作るのにマウスを使った球体軌道なカメラがあると便利なんだけど、よく作り方を忘れるのでスクリプトごとここに張り付けておく。

  • 球体座標でググれば理論とか出てくるので本当にスクリプトだけ張ります。

  • 使い方は簡単で、Cameraにこのスクリプトを入れて、targetに注視したいオブジェクトをドラックアンドドロップ。もし何も入ってなかったら"Player"タグを自動で探して入れます。

CameraController.cs
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
    [SerializeField]Transform target;
    [SerializeField]float spinSpeed = 1.0f;

    Vector3 nowPos;
    Vector3 pos = Vector3.zero;
    Vector2 mouse = Vector2.zero;
    // Use this for initialization
    void Start () {
        // Canera get Start Position from Player
        nowPos = transform.position;

        if(target == null)
        {
            target = GameObject.FindWithTag("Player").transform;
            Debug.Log("player didn't setting. Auto search 'Player' tag.");
        }

        mouse.y = 0.5f; // start mouse y pos ,0.5f is half
	}
	
	// Update is called once per frame
	void Update () {

        // Get MouseMove
        mouse += new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")) * Time.deltaTime * spinSpeed;
        // Clamp mouseY move
        mouse.y = Mathf.Clamp(mouse.y, -0.3f + 0.5f, 0.3f + 0.5f);

        // sphere coordinates
        pos.x = Mathf.Sin(mouse.y * Mathf.PI) * Mathf.Cos(mouse.x * Mathf.PI) ;
        pos.y = Mathf.Cos(mouse.y * Mathf.PI) ;
        pos.z = Mathf.Sin(mouse.y * Mathf.PI) * Mathf.Sin(mouse.x * Mathf.PI) ;
        // r and upper
        pos *= nowPos.z;
        
        pos.y += nowPos.y;
        //pos.x += nowPos.x; // if u need a formula,pls remove comment tag.

        transform.position = pos + target.position;
        transform.LookAt(target.position);
    }
}

完全にフリーなので自由に使ってください。

25
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?