我正在尝试统一实施RADAR传感器。我目前正在使用球体投射来识别物体并测量其速度和距离。此时,即使在球体投射的半径范围内有多个物体,它也只能识别最近的物体。如何让它识别球体内的所有物体。?
任何帮助将不胜感激.. 这就是我现在所做的,它只识别识别最近的对象。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spherecast : MonoBehaviour
{
Rigidbody rb;
public GameObject curobject;
public float radius;
public float maxdist;
public LayerMask layermask;
public float velocity;
public Time deltatime;
public Vector3 previous;
private Vector3 origin;
private Vector3 direction;
private float hitdist;
// Use this for initialization
void Start()
{
previous = curobject.transform.position;
}
// Update is called once per frame
void Update()
{
velocity = hitdist/Time.deltaTime;
origin = transform.position;
direction = transform.forward;
RaycastHit hit;
if (Physics.SphereCast(origin, radius, direction, out hit, maxdist, layermask, QueryTriggerInteraction.UseGlobal))
{
curobject = hit.transform.gameObject;
hitdist = hit.distance;
Debug.Log("Distance" + hitdist);
velocity = ((curobject.transform.position - previous).magnitude) / Time.deltaTime;
previous = curobject.transform.position;
Debug.Log("Velocity" + velocity);
// Debug.Log("Velocity = " + velocity);
}
else
{
hitdist = maxdist;
curobject = null;
}
}
private void ondrawgizmosselected()
{
Gizmos.color = Color.red;
Debug.DrawLine(origin, origin + direction * hitdist);
Gizmos.DrawWireSphere(origin + direction * hitdist, radius);
}
}
答案 0 :(得分:3)
如何让它识别球体内的所有物体。?
我认为你需要使用SphereCastAll代替SphereCast。
https://docs.unity3d.com/ScriptReference/Physics.SphereCastAll.html
<强>答案:强>
“与Physics.SphereCast类似,但此函数将返回球体扫描相交的所有命中。”
它返回一个RaycastHit []。