0
1

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】円形状の移動制限のかけ方

Posted at

#Script

test
	public GameObject centerObj;            //中心となるオブジェクト(ゲームオブジェクトじゃなくても中心点がわかればOK)

	[SerializeField, Header("半径")]
	float radius;

	[SerializeField, Header("速さ")]
	float speed;
	
	// Update is called once per frame
	void Update ()
	{
		Move();
		Restriction();
	}

	void Move()
	{
		//手動で動かせるように(円形の移動制限には関係ありません)
		transform.position += new Vector3(Input.GetAxis("Horizontal") *speed*Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0);
	}

	/// <summary>
	/// 円形の移動制限
	/// </summary>
	void Restriction()
	{
		//自身と円形に移動制限させたい位置の中心点との距離を測り半径以上になっていれば処理
		if (Vector3.Distance(transform.position,centerObj.transform.position)>radius)
		{
			//中心点から自身までの方向ベクトルを作る
			Vector3 nor=transform.position-centerObj.transform.position;
			//作った方向ベクトルを正規化する
			nor.Normalize();
			//方向ベクトル分半径に移動させる
			transform.position = nor * radius;
		}
	}

#どんな場合に使うの?
自分は自作バーチャルパッドを作った時に使いました

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?