从sphereCast获取信息

时间:2015-05-05 13:04:23

标签: c# unity3d

我知道如何从RayCast获取信息,但在sphereCast上找不到任何好处。 当我向敌人射击时,我可以发现它的健康成分,并减少它的健康。

这是代码:

    shootRay.origin = transform.position;
    shootRay.direction = transform.forward
    if (Physics.Raycast(shootRay, out shootHit, 100f, shootableMask))
    {
       EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>();
        if (enemyHealth != null)
        {
            enemyHealth.TakeDamage(damagePerShot, shootHit.point);
        }
    }

现在我想用SphereCast做类似的事情,但是我想要检测击中区域内的所有敌人并减少他们的健康,而不是一个敌人。

if (Physics.SphereCast(shootRay, 5f, out shootHit, 100f, shootableMask))
    {
       // ???
    }

1 个答案:

答案 0 :(得分:1)

根据此(http://answers.unity3d.com/questions/486261/how-can-i-raycast-to-multiple-objects.html),您需要做的就是使用RaycastAll

实施例

void Update() {
    RaycastHit[] hits;
    hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
    int i = 0;
    while (i < hits.Length) {
        RaycastHit hit = hits[i];
        Renderer rend = hit.transform.GetComponent<Renderer>();
        if (rend) {
            rend.material.shader = Shader.Find("Transparent/Diffuse");
            rend.material.color.a = 0.3F;
        }
        i++;
    }
}