LoginSignup
7
8

More than 5 years have passed since last update.

Unity2DでRaycastを使って座標からGameObjectを取得する

Posted at

Raycastの練習として、やってみました。
ほかの取り方もあるかもしれません。

Vector3 pos = new Vector3(/* 好きな値 */);
RaycastHit2D hit = Physics2D.Raycast(pos, new Vector3(0, 0, 1), 100);

// 可視化
Debug.DrawRay(pos, new Vector3(0, 0, 100), Color.blue, 1);

// コンソールにhitしたGameObjectを出力
Debug.Log(hit.collider);

このhit.colliderでGameObjectを取れます。

マウス座標からもとれるよ

このやり方だと、遠回りになるかもしれませんが、
マウス座標からとるのも簡単です!
上のコードの最初の行を、次のように変えるとできます。

Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
7
8
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
7
8