【问题标题】:C# unity Changing a variable using ray cast hit informationC# unity 使用光线投射命中信息更改变量
【发布时间】:2023-03-05 23:12:01
【问题描述】:

这个游戏中的相机有一个目标,可以通过点击其他模型来改变,然后成为相机焦点,下面的脚本是我到目前为止得到的,但是每次我点击游戏中的一个对象时,目标只是说没有,而不是任何模型。

Ray toMouse = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
bool didHit = Physics.Raycast(toMouse, out hitInfo);

if (didHit)
{
    if (hitInfo.collider.tag == "Cell" && Input.GetMouseButtonDown(0))
    {
        Debug.Log("Cell hit");

        target = hitInfo.transform.Find(gameObject.name);       
    }
}

【问题讨论】:

  • 什么是gameObject.name?这里似乎缺少一些代码。
  • 我认为可以将光线投射命中的对象名称转换为目标名称。

标签: c# unity3d camera raycasting


【解决方案1】:

如果这个脚本在相机上,应该这样做:

GameObject target;
// or
Transform target;

void Update()
{
    if(Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit))
        {
            target = hit.transform.gameObject;
            // or
            target = hit.transform;
        }
    }   
}

【讨论】:

  • 非常感谢,我知道我做错了什么,现在可以正常工作了。
  • @ryand444 。对你有益。请接受答案,因为它对您有帮助。
猜你喜欢
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多