RaycastHit2D hit = Physics2D.Linecast(targetPosition, targetPosition + new Vector2(x, y));
猜测是linecast函数一旦检测到第一个碰撞体之后就会停止检测。
所以把自身检测进去之后就不会检测墙了。估计Physics.Raycast函数也有此性质,这里要注意一下。
2、
Unity 2D两种常用判断点击的方法
http://wiki.ceeger.com/script/unityengine/classes/physics2d/physics2d.raycast
1.Raycast法
原理相同于3D中得Raycast法,具体使用略有区别。
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null)
{
Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
//and do what you want
}
2.Overlap法
http://wiki.ceeger.com/script:unityengine:classes:physics2d:physics2d.overlappointall
个人觉得这个方法对于2D更合适一些,判断点击的点落在了哪些collider中。
Collider2D[] col = Physics2D.OverlapPointAll(Camera.main.ScreenToWorldPoint(Input.mousePosition));
if(col.Length > 0)//数组长度不为空
{
foreach(Collider2D c in col)
{
//do what you want
}
}
http://blog.csdn.net/myarrow/article/details/30213689