やまめも

【 ゲーム開発・日々のことについて 】

Physics2D.Raycast

3D用の当たり判定は2D用では使えない。
コードを2Dように書く必要がある。

2D用、例1

using UnityEngine;
using System.Collections;

public class ObjectManager3 : MonoBehaviour {

	public GameObject Prefab;

	void Start () {
	}

	void Update () {
		if(Input.GetMouseButtonDown(0)){
			print ("clicked");
			CreatEmpty();
		}
	}
	void CreatEmpty(){
		Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero);
		Vector2 hitPoint;
		if(hit){
            Bounds rect =  hit.collider.bounds;
            if(rect.Contains(worldPoint)){
            	print ("hit!!");
            	hitPoint= hit.point;
				print ("hit.point = "+ hitPoint);
				Instantiate(Prefab, hitPoint, Quaternion.identity);
            }
		}
	}
}

3D用

using UnityEngine;
using System.Collections;

public class ObjectManager2 : MonoBehaviour {

	public GameObject Prefab;

	void Start () {
	}

	void Update () {
		if(Input.GetMouseButtonDown(0)){
			print ("clicked");
			CreatEmpty();
	}
	void CreatEmpty(){
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		Vector3 hitPoint;
		RaycastHit hit;
		if(Physics.Raycast(ray, out hit, Mathf.Infinity)){
			if( hit.collider.gameObject == null ){

				return;
			}
			print ("hit!!");
			hitPoint= hit.point;
			print ("hit.point = "+ hitPoint);
			hitPoint.z = 2;
			Instantiate(Prefab, hitPoint, Quaternion.identity);

		}
	}

}

albatrus.com

追記2015/06/17
例2

Vector2 worldPoint = Camera.main.ScreenToWorldPoint(mp);
RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero);
Vector2 hitPoint;
if(hit){
    Bounds rect =  hit.collider.bounds;
    if(rect.Contains(worldPoint)){
    	if( hit.transform.gameObject.tag == "ItemObj"){
    		print("ItemObjだよ!!!");
    	}
    }
}