Unity3d通过射线来实现点击地面,获取点击坐标

using UnityEngine;
using System.Collections;

public class RayCastTest : MonoBehaviour
{
    public float validTouchDistance; //200
    public string layerName;         //"Ground"

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);  //摄像机需要设置MainCamera的Tag这里才能找到
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo , validTouchDistance , LayerMask.GetMask(layerName) ))
            {
                GameObject gameObj = hitInfo.collider.gameObject;
                Vector3 hitPoint = hitInfo.point;
                Debug.Log("click object name is " + gameObj.name + " , hit point " + hitPoint.ToString() );
            }
        }
    }
}

你可能感兴趣的:(unity3d)