所以,我有一个包含游戏对象的列表,我非常不确定如何获得每个对象的距离、碰撞和方向。使用 SphereCast 来满足我的需求是合适的,因为我知道只有类函数才能为我做这件事。我编写了代码来完成任务,但它只为列表中的 1 个游戏对象获取数据,在所有这些对象中,我希望从列表中的所有游戏对象中获取数据。有什么想法可以更改代码或方法吗?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class example : MonoBehaviour {
RaycastHit hit;
Vector3 direction;
public static List<float> sphereCast = new List<float>();
void Update() {
CharacterController charCtrl = GetComponent<CharacterController>();
foreach(GameObject g in xmlreaderUnityObject.unityGameObjectsToCDP)
{
Vector3 p1 = g.transform.position;
if (Physics.SphereCast(p1, charCtrl.height / 2, g.transform.forward, out hit,1))
{
float distance = 0;
float angleBetween = 0;
float contact = 0;
if(hit.collider.enabled)
{
direction = hit.transform.position - p1;
angleBetween = Vector3.Angle(g.transform.forward, direction);
contact = 1;
distance = hit.distance;
}
print("Distance: "+ distance + " Collision: " + contact + " Direction: " + angleBetween + " hit point: "
+hit.point + " player position: " + p1);
sphereCast.Add(contact);
sphereCast.Add(distance);
sphereCast.Add(angleBetween);
}
}
}
}