简体   繁体   English

如何获取列表中每个游戏对象的距离,碰撞和方向?

[英]How to get the Distance, Collision and Direction for each game object in my list?

So, I've a list with a game objects and I'm very uncertan about how to get the distance, collistion, direction for each of them. 因此,我有一个包含游戏对象的列表,对于如何获取每个对象的距离,匹配度和方向,我非常不确定。 It is sutable to use the SphereCast, to cover my needs, becouse I know it is only class functions that can do it for me. 使用SphereCast满足我的需求是可行的,因为我知道只有类函数才能为我做这件事。 I wrote the code to accomplish the task, but its grabbing the data just for 1 game object in my list, insted of all of them, I wish to grab data from all game object in my list. 我编写了代码来完成任务,但是它只是从列表中的一个游戏对象中获取数据,而在所有这些对象中,我希望从列表中的所有游戏对象中获取数据。 Any ideas to change the code or approaches? 有任何改变代码或方法的想法吗?

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);
            }
        }

    }
}

The reason is because it only hit one GameObject. 原因是因为它仅命中了一个GameObject。 I have set a Scene up where you it shows all the GameObjects it hit + which GameObject that send it. 我已经设置了一个场景,在其中您可以显示所有命中的游戏对象+发送该游戏对象的游戏对象。 Project Example 项目实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM