OkakenProject

ちょっとした スキマ時間のお手伝い

【Unity】World座標とScreen座標の変換

やりたいこと

画面タップでオブジェクト選択するようにしたい。

結論

Camera.main.ScreenToWorldPoint(Input.mousePosition)を使ってScreen座標をWorld座標に変換する

Input.mousePositionで取得するのはScreen座標(左下0,0)
transform.positionで取得するのはWorld座標(中央0,0)

なのでそのままだと当たり判定が直感的にできない

2つを変換するメソッドがCamera.main.ScreenToWorldPointなので、そのあとで座標位置を比較して当たり判定する。画面タップした時の位置をWorld座標で取得する部分。

  • if (Input.GetMouseButtonDown(0))
  •         {
  •             Vector2 beforeWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
  •             beforePosIndex_x = getTapPosToPanelIndex_x(beforeWorldPoint.x);
  •             beforePosIndex_y = getTapPosToPanelIndex_y(beforeWorldPoint.y);
  •             buttonDownIndex_x = beforePosIndex_x;
  •             buttonDownIndex_y = beforePosIndex_y;
  •             nowTapping = true;
  •         }
  • }