2
2

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.

[めもめも]ターゲットの方へ向く、移動する uGui 2D

Posted at

自分用めもめも

2Dの話
2Dの話
2Dの話!!!!!

sample
	
		//2Dだけ 
		Transform playerTrans = null; 		//自分自身  transform
		Transform targetTrans = null;		//見たいものtransform



		//目標までのベクトルを求める;
		Vector3 subVec = targetTrans.localPosition - playerTrans.localPosition;

		//角度を変える;
		float angle = Mathf.Atan2(subVec.y, subVec.x) * Mathf.Rad2Deg;

        //これで目的のほうへ向いてくれる;
		playerTrans.localEulerAngles = new Vector3(0, 0, angle);


		//右クリックしている間 目的地のほうにすすみます;
		if(Input.GetMouseButton(1)){

			Vector3 v = Vector3.zero;
#if false
			//角度から移動方向を求める
			float radAngle = angle * Mathf.Deg2Rad;
			v.x = Mathf.Cos(radAngle);
			v.y = Mathf.Sin(radAngle);
#else
			//2点間の距離から移動方向を求める;
			v = subVec.normalized;
#endif
			//ここで好きな速さにできる;
			//v *= speed;	
			playerTrans.transform.localPosition += v;
		}

2点間の距離から移動を求めたほうが計算そんなしなくていいかもしれません

おまけ

タッチ位置の取得

omake
	Vector2 getMousePos()
	{

		//public int screenW = 1136;
		//public int screenH = 640;
		
		Vector2 pos = (Vector2)Input.mousePosition - new Vector2(Screen.width / 2, Screen.height / 2);
		float aspect = (float)Screen.width / (float)Screen.height;
		pos.x = pos.x * ((float)screenH / (float)Screen.width) * aspect;
		pos.y = pos.y * ((float)screenH / (float)Screen.height);

		pos.x = Mathf.Min(pos.x, screenW / 2);
		pos.y = Mathf.Min(pos.y, screenH / 2);

		pos.x = Mathf.Max(pos.x, screenW / -2);
		pos.y = Mathf.Max(pos.y, screenH / -2);



		return pos;
	}
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?