gpt4 book ai didi

c# - 检查脚本相同时哪个对象与另一个对象发生碰撞

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:38 26 4
gpt4 key购买 nike

两个动画汽车对象都包含刚体盒子碰撞器以及一个带有OnTriggerEnter 事件脚本

现在我想检查两辆车都在运行时哪辆车撞到了另一辆车。意味着如果 A 击中 B 或 B 击中 A 因为两者具有相同的脚本和相同的事件,那么这两个事件都会触发。如何识别它是谁打的???

请记住,请不要推荐我使用 Raycast,它很昂贵

例如我制作了两个立方体,添加了盒子对撞机和刚体以及一个包含(或检查)的脚本

void OnTriggerEnter(Collider c) {
Debug.Log("GameObject is : " + gameObject.name + " and collider : " + c.name);

}

现在,当我触发两个对象时,无论我将 A 对象击中 B 还是将 B 对象击中 A,触发顺序都保持不变。我将如何区分它?

最佳答案

我看到几种方法,其中这是最简单的:

编辑:注意 - RigidBidy 需要有速度,我的意思是你需要用 RigidBody 使用 AddForce 或任何移动对象其他基于物理的运动。

  1. 检查速度。获取每辆车的 RigidBody 并检查 velocity - 具有更高 velocity Vector3 的那个是命中的。注意这里需要使用投影。

    void OnTriggerEnter(Collider c) 
    {
    Debug.Log("GameObject is : " + gameObject.name + " and collider : " + c.name);

    Vector3 directionB = this.transform.position - c.transform.position;
    Vector3 directionA = c.transform.position - this.transform.position;

    Vector3 rawVelocityA = this.GetComponent<Rigidbody> ().velocity;
    Vector3 rawVelocityB = c.GetComponent<Rigidbody> ().velocity;

    Vector3 realSpeedA = Vector3.Project (rawVelocityA, directionA);
    Vector3 realSpeedB = Vector3.Project (rawVelocityB, directionB);

    if (realSpeedA.magnitude > realSpeedB.magnitude)
    {
    Debug.Log ("A hit B");
    }
    else if (realSpeedB.magnitude > realSpeedA.magnitude)
    {
    Debug.Log ("B hit A");
    }
    else
    {
    Debug.Log ("A hit B and B hit A");
    }
    }

编辑:由于您没有使用物理学来移动汽车,因此您需要以其他方式计算速度

我建议这样:

在每辆车上都有一个脚本 SpeedCalculator.cs。

public class SpeedCalculator : MonoBehaviour 
{
public float Velocity
{
get
{
return velocity;
}
}
private float velocity;

private Vector3 lastPosition;

void Awake()
{
lastPosition = transform.position;
}

void Update()
{
velocity = transform.position - lastPosition;
lastPosition = transform.position;
}
}

然后不是从 RigidBody 获取速度,而是从 SpeedCalculator 获取速度:

void OnTriggerEnter(Collider c) 
{
Debug.Log("GameObject is : " + gameObject.name + " and collider : " + c.name);

Vector3 directionB = this.transform.position - c.transform.position;
Vector3 directionA = c.transform.position - this.transform.position;

Vector3 rawVelocityA = this.GetComponent<SpeedCalculator> ().Velocity;
Vector3 rawVelocityB = c.GetComponent<SpeedCalculator> ().Velocity;

Vector3 realSpeedA = Vector3.Project (rawVelocityA, directionA);
Vector3 realSpeedB = Vector3.Project (rawVelocityB, directionB);

if (realSpeedA.magnitude > realSpeedB.magnitude)
{
Debug.Log ("A hit B");
}
else if (realSpeedB.magnitude > realSpeedA.magnitude)
{
Debug.Log ("B hit A");
}
else
{
Debug.Log ("A hit B and B hit A");
}
}

关于c# - 检查脚本相同时哪个对象与另一个对象发生碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37782373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com