unity 射线检测2D物体
作者:互联网
Vector3 mousepoint = Input.mousePosition;
mousepoint.z =Mathf.Abs( Camera.main.transform.position.z);//非常重要,如果不是正交摄像机,就需要转换
var v = Camera.main.ScreenToWorldPoint(mouspoint);
RaycastHit2D hit = Physics2D.Raycast(v, Vector2.zero,0);
if (hit.collider)
{
Debug.Log(hit.collider.name);
}
首先需要挂载Collider2D,然后摄像机如果不是正交,需要mathf转换成正的坐标
第二种办法是网上找的
/// <summary>
/// 返回鼠标的坐标
/// </summary>
/// <returns></returns>
public static Vector2 GetMousePoint()
{
Vector3 screenPos = Input.mousePosition;
Vector3 p0 = Camera.main.transform.position;
screenPos.z = p0.z;
Vector3 p1 = Camera.main.ScreenToWorldPoint(screenPos);
float h2 = 0.0f - p0.z;
float h1 = p1.z - p0.z;
Vector3 dir = p1 - p0;
dir.z = 0.0f;
float d1 = dir.magnitude;
float d2 = d1 * h2 / h1;
Vector3 p2 = p0 + dir.normalized * d2;
p2.z = 0;
return p2;//将正确的鼠标屏幕坐标换成世界坐标交给物体
}
标签:p0,float,Vector3,2D,射线,unity,Camera,main,dir 来源: https://blog.csdn.net/qq_42228424/article/details/120924882