-1

在尝试进行 raycast 时,我无法让它工作,我尝试改变符号,我尝试在外面使用 raycasthit 并通过它。我只是无法让它工作..

public int count = 0;
public Transform origin;
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    if (Input.GetKey(KeyCode.Mouse1))
    {
        Physics.Raycast(origin.position , RaycastHit hitinfo);
        if (hitinfo.collider.tag == "enemy")
        {
            count++;
        }
    }
4

2 回答 2

1

你必须声明一个 RaycastHit - 当然这在你的 Physics.Raycast 调用之外。

请参阅统一文档中的此代码 - 您还可以传入图层蒙版:

using UnityEngine;
// C# example.

public class ExampleClass : MonoBehaviour
{
    // See Order of Execution for Event Functions for information on FixedUpdate() and Update() related to physics queries
    void FixedUpdate()
    {
        // Bit shift the index of the layer (8) to get a bit mask
        int layerMask = 1 << 8;

        // This would cast rays only against colliders in layer 8.
        // But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
        layerMask = ~layerMask;

        RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Did Hit");
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log("Did not Hit");
        }
    }
}
于 2021-01-27T19:03:38.463 回答
0

问题是没有重载函数

Physics.Raycast(origin.position , RaycastHit hitinfo);

这意味着您可以将许多东西放入 Raycast 函数中,但 a(Vector3, RaycastHit)不是组合之一。我经常使用以下方法:

/* Define the point of origin for the raycast */
var origin = transform.position; // From the player

/* Define the direction the raycast will be going in from the origin */
var dir = transform.forward; // Infront of the player

/* Define a ray */
Ray ray = new Ray(origin, dir);

/* Create a storage for the results */
HitInfo hit;

/* Check to see if we hit something */
if (Physics.Raycast(ray, out hit)){
    // Yes we did hit something
    print("We hit an object");
} 

如果我们把它放到一个 propper 函数中来获取相机正在查看的标签:

public string GetTagOfLookingAt () {
    RaycastHit hit;
    Ray ray = Camera.Main.ScreenPointToRay(Input.mousePosition);
        
    if (Physics.Raycast(ray, out hit)) {
        return hit.gameobject.tag;
    } else {
        return string.Empty;
    }
}
于 2021-01-27T22:11:17.750 回答