【スポンサーリンク】

【Unity 3D】クリック(タップ)先のゲームオブジェクトおよび座標の取得

Physics.Raycastでクリック先のオブジェクトと交点座標を取得できる。引数に必要なRayオブジェクトはメインカメラ一つの場合、
Camera.main.ScreenPointToRay(Input.mousePosition)
で取得できる。

なお、Physics.Raycastの返り値はbool値となっており、肝心のクリック先オブジェクトは参照渡しした変数に返すため、コードの見やすさを考慮すると用途に応じてラップしたほうが良いと思われる。

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
	void Update() {
		if(Input.GetKeyDown(KeyCode.Mouse0)) {
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			Debug.Log(HitGameObject(ray) == null ? null : HitGameObject(ray).name);
			Debug.Log(HitPoint(ray));
		}
	}

	//クリック先のオブジェクトを取得する関数
	GameObject HitGameObject (Ray ray) {
		RaycastHit hit;
		return Physics.Raycast(ray, out hit) ? hit.transform.gameObject : null;
	}

	//クリック先とオブジェクトの交点座標を取得する関数
	Vector3? HitPoint (Ray ray) {
		RaycastHit hit;
		return Physics.Raycast(ray, out hit) ? hit.point : (Vector3?)null;
	}

}
【スポンサーリンク】