ScreenToWorldPoint(2D上でお絵描きしたいとき)
2Dでの「Camera.main.ScreenToWorldPoint」の扱いに困った。
これは、「スクリーン座標をワールド座標に変換する関数」であるが、これを2Dで使うたいとき、カメラのプロパティ「Projection」を「Orthographic」(2D用)に設定してあげなければならない。
082 ScreenToWorldPoint関数の注意点 [stepism@Unityメモ]
using UnityEngine; using System.Collections; public class ObjectManager : MonoBehaviour { // 子要素 public GameObject Child; // 親要素 public GameObject Prefab; public GameObject NowParent; public Vector2 LastPos; void Start () { LastPos = transform.position; } void Update () { if(Input.GetMouseButtonDown(0)){ CreatEmpty(); } if(Input.GetMouseButton(0)){ DrawLine(); } if(Input.GetMouseButtonUp(0)){ if( NowParent != null){ NowParent.AddComponent("Rigidbody2D"); NowParent.layer = 9; NowParent = null; } } } void CreatEmpty(){ // if(PlayerPrefs.GetInt("play") == 1){ print("マウスの位置 "+Input.mousePosition); Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero); Vector2 hitPoint; if(hit){ if( hit.transform.gameObject.layer == 8){ Bounds rect = hit.collider.bounds; if(rect.Contains(worldPoint)){ // vector2 hitPoint= hit.point; print ("hit!! hitPoint = "+ hitPoint); Vector2 hitPointRondam = hitPoint + new Vector2(Random.Range(0f, 0.1f), Random.Range(0f, 0.1f)); NowParent = Instantiate(Prefab, hitPointRondam, Quaternion.identity) as GameObject; NowParent.transform.parent = gameObject.transform; NowParent.name = "Parent"; } } else{ print ("そこは範囲外だよ"); return; } } // } } void DrawLine(){ // if(PlayerPrefs.GetInt("play") == 1){ Vector2 Pos = Input.mousePosition; // if(Pos == LastPos){ // return; // } Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Pos); RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero); Vector2 hitPoint; if(hit){ Bounds rect = hit.collider.bounds; if(rect.Contains(worldPoint)){ if( hit.transform.gameObject.layer == 8){ hitPoint= hit.point; print ("hit.point = "+ hitPoint); GameObject obj = Instantiate(Child, hitPoint, transform.rotation) as GameObject; obj.layer = 9; obj.transform.parent = NowParent.transform; obj.name = "child"; LastPos = Pos; }else{ return; } } } // } } }