Unity - Phyics.Raycast returns 错误
Unity - Phyics.Raycast returns false
我创建了一个空的游戏对象并附加了 .cs 文件。我尝试在鼠标单击位置加载预制件(.obj 文件)。我的代码是:
Ray ray;
RaycastHit hit;
public GameObject prefab;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
ray=Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
GameObject obj = Instantiate(prefab, new Vector3(hit.point.x, hit.point.y, hit.point.z), Quaternion.identity) as GameObject;
}
else
{
Debug.Log("Physics.Raycast returns false");
}
}
Raycast returns 每次都是错误的。
您需要将 Collider 添加到您的 GameObject
对于 Physics3D
Description
Casts a ray against all colliders in the scene.
Physics.Raycast 脚本 API 文档 here.
对于 Physics2D
Description
Casts a ray against colliders in the scene.
A raycast is conceptually like a laser beam that is fired from a point
in space along a particular direction. Any object making contact with
the beam can be detected and reported.
Physics2D.Raycast 脚本 API 文档 here.
您需要将 3d 对撞机附加到您的 sprite 游戏对象才能被光线投射检测到。
See my complete answer here
我创建了一个空的游戏对象并附加了 .cs 文件。我尝试在鼠标单击位置加载预制件(.obj 文件)。我的代码是:
Ray ray;
RaycastHit hit;
public GameObject prefab;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
ray=Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
GameObject obj = Instantiate(prefab, new Vector3(hit.point.x, hit.point.y, hit.point.z), Quaternion.identity) as GameObject;
}
else
{
Debug.Log("Physics.Raycast returns false");
}
}
Raycast returns 每次都是错误的。
您需要将 Collider 添加到您的 GameObject
对于 Physics3D
Description
Casts a ray against all colliders in the scene.
Physics.Raycast 脚本 API 文档 here.
对于 Physics2D
Description
Casts a ray against colliders in the scene.
A raycast is conceptually like a laser beam that is fired from a point in space along a particular direction. Any object making contact with the beam can be detected and reported.
Physics2D.Raycast 脚本 API 文档 here.
您需要将 3d 对撞机附加到您的 sprite 游戏对象才能被光线投射检测到。
See my complete answer here