Unity3d OnTriggerEnter碰撞方向检测

时间:2015-04-27 12:32:38

标签: vector unity3d collision-detection euler-angles

好的,所以我相信这个概念应该很简单。然而,答案是我的想法。编辑背景。 "其他"对象和带有此代码的gameObject都有球形碰撞器作为触发器,这个gameObject有一个附加用于移动的CharacterController,但都没有RigidBodies。我的目标是这个(玩家对象,自动移动PacMan风格)杀死它运行的东西,但只有它面对它们,否则,它应该受到伤害。我的问题是弄清楚如何判断它是否面向对象。要完成图片,moveDirection可以是以下之一(Vector3.Up,.Down,.Left或.Right),因为播放器和NPC仅沿X和Y轴移动(带有3D游戏对象的正交相机) )

〜老方法

    void OnTriggerEnter (Collider other)
    {

        if (other.gameObject.tag == "Human") {
            RaycastHit hit;
            if (Physics.Raycast (transform.position, moveDirection, out hit)) {
                StartCoroutine (eatWithBlood (1, other.gameObject.GetComponent<NPCController> ()));
            } else {
                TakeDamage (other.gameObject.GetComponent<NPCController> ().attack);
            }

        } 
    }

我还尝试了以下代码,效果更好一些。数学运算并不是很正确,所以即使角度在45到-45之间,玩家仍然会被击晕&#34;并受到伤害。如果需要其他变量以进行更准确的计算,新方法已预先配置为扩展。 faceDirection变量是up = 0,right = 1,down = 2,left = 3,它们也对应于他们的Vector3.up,左,右和右队列。

〜新方法

void OnTriggerEnter (Collider other)
    {

        if (other.gameObject.tag == "Human") {
            float angle = Vector3.Angle (transform.forward, other.gameObject.transform.position);
            Debug.Log ("Angle: " + angle + "; my forward: " + faceDirection + "; other forward: " + other.gameObject.GetComponent<NPCController> ().faceDirection + " ... " + Time.time);
            if (IAteHim (faceDirection, other.gameObject.GetComponent<NPCController> ().faceDirection, angle)) {
                other.gameObject.GetComponent<NPCController> ().EatMe ();
                StartCoroutine (eatWithBlood (1, other.gameObject.GetComponent<NPCController> ()));
            } else {
                GameObject poof = PoofPooler.poof.GetPooledObject ();
                if (poof != null) {
                    poof.transform.position = Vector3.Lerp (transform.position, other.gameObject.transform.position, 0.5f);
                    poof.GetComponent<PoofControl> ().reactivated = true;
                    poof.SetActive (true);

                }
                other.gameObject.GetComponent<NPCController> ().MakeInvincible ();
                TakeDamage (other.gameObject.GetComponent<NPCController> ().attack, 2.0f);
            }


        }
    }

    bool IAteHim (int myDirection, int otherDirection, float angle)
    {
        if (angle > -45 && angle < 45) { // I'm facing toward yummies
            return true;
        } else {
            return false;
        }

    }

1 个答案:

答案 0 :(得分:0)

变化

float angle = Vector3.Angle (transform.forward, other.gameObject.transform.position);

Vector3 direction = other.gameObject.transform.position - transform.position;
float angle = Vector3.Angle (transform.forward, direction);