にしのクエスト2

情報処理技術者試験と資格学校講師の日常

20221224103753

Unityで学ぶプログラミング TIPS(7)球体移動

一回中断したくせに、またUnityざますよ。

f:id:koharuwest:20190726220733p:plain


マウスの動きに合わせて、カメラがある物体を中心に
動くというプログラムを球体移動というそうです。

ゲームとかでよく使われる技で。色々な方が、色々な
方法で実現されているようですが。

にしの流にチューンしてご紹介します。

ちなみに、プログラムはメインカメラにアタッチして
みてください。

また、プログラムに対象となるオブジェクトを指定し
てあげないと動きませんので、よろしく!

 //ターゲットになる物体 あとでobject放り込んでね
 public Transform target;
 //回転速度
 public float Speed = 2.0f;
 //物体との距離
 float distance = 5.0f;
 //現在位置
 Vector3 nowPos;
 //原点 xyz
 Vector3 pos =new Vector3(0,0,0);
 //マウスの位置 xy
 public Vector2 mouse =new Vector2(0,0);

void Start(){
 
//まず現在位置を取得
nowPos = transform.position;

}


void
 Update(){

// マウスをクリックしたら

if (Input.GetMouseButton(0)){
//マウスの動く座標*時間*速度を計算する
mouse += new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")) * Time.deltaTime * Speed;
}

//マウスのY座標に制限をかける

mouse.y = Mathf.Clamp(mouse.y, -0.3f + 0.5f, 0.3f + 0.5f);

//球面座標系変換

pos.x = distance * Mathf.Sin(mouse.y * Mathf.PI) * Mathf.Cos(mouse.x * Mathf.PI);

pos
.y = -distance * Mathf.Cos(mouse.y * Mathf.PI);

pos
.z = -distance * Mathf.Sin(mouse.y * Mathf.PI) * Mathf.Sin(mouse.x * Mathf.PI);

pos *= nowPos.z;

pos.y += nowPos.y;

//座標の更新
transform.position = pos + target.position;

//そっち向かせる

transform.LookAt(target.position);