unity3d 如何计算碰撞损伤

ih99xse1  于 2023-02-16  发布在  其他
关注(0)|答案(1)|浏览(144)

所以我想让一个物体在每次与其他物体碰撞时都受到伤害
我的方法是计算旧位置和新位置,并通过归一化差值获得方向,然后在碰撞输入时,我获得碰撞点的方向,然后使用单位向量3。Angular 之后,我使用"m * g * cos(X)"计算力,但似乎无法正常工作
顺便说一下我用刚体
代码:

Vector3 direction;
public Rigidbody rb;

float mass;
float damageAmount;
float speed;
float angle;

void Awake()
{
 rb = GetComponent<Rigidbody>();
 mass = rb.mass;

}

void Update() 
{

 
}


void OnCollisionEnter(Collision info)
{
    direction = gameObject.GetComponent<playerMovement>().moveVelocity.normalized;
    speed = gameObject.GetComponent<playerMovement>().actualSpeed;

    foreach (ContactPoint contact in info.contacts)
    {
            Vector3 pointDirection;
            pointDirection =(transform.position - contact.point).normalized;
           
        angle = Vector3.Angle(direction,-pointDirection);
        float force = mass* Physics.gravity.y *Mathf.Cos(angle);
        Debug.Log(force+" "+angle);
    }
}

我获得方向的方法是在Update()中获得当前位置,并在移动之前在FixedUpdate中获得旧位置

ff29svar

ff29svar1#

看起来您的方法走上了正确的轨道,但是您的实现可能存在一些问题。
首先,您可能需要考虑将计算对象方向和速度的代码移到FixedUpdate()方法,因为该方法专门为物理计算而设计,并且以固定的时间间隔调用,这有助于确保计算的准确性和一致性。
其次,您使用的Angular 计算可能并非在所有情况下都准确。()来计算移动方向和碰撞点之间的Angular ,当对象以不垂直于移动方向的Angular 碰撞时,可能无法给予正确的Angular 。相反,你可以考虑使用运动方向和碰撞点法线的点积,它将给予它们之间夹角的余弦,计算如下:

Vector3 normal = contact.normal;
angle = Mathf.Acos(Vector3.Dot(direction, normal));

最后,您可能需要确保将力施加到正确的对象上。在当前代码中,您正在计算力,但没有将其施加到任何对象上。要将力施加到对象上,可以对对象的Rigidbody组件使用AddForce()方法,如下所示:

rb.AddForce(-pointDirection * force, ForceMode.Impulse);

将所有这些放在一起,您更新的代码可能类似于以下内容:

Vector3 direction;
public Rigidbody rb;

float mass;
float damageAmount;
float speed;
float angle;

void Awake()
{
    rb = GetComponent<Rigidbody>();
    mass = rb.mass;
}

void FixedUpdate()
{
    direction = gameObject.GetComponent<playerMovement>().moveVelocity.normalized;
    speed = gameObject.GetComponent<playerMovement>().actualSpeed;
}

void OnCollisionEnter(Collision info)
{
    foreach (ContactPoint contact in info.contacts)
    {
        Vector3 pointDirection = (transform.position - contact.point).normalized;
        Vector3 normal = contact.normal;
        angle = Mathf.Acos(Vector3.Dot(direction, normal));
        float force = mass * Physics.gravity.y * Mathf.Cos(angle);
        Debug.Log(force + " " + angle);

        rb.AddForce(-pointDirection * force, ForceMode.Impulse);
    }
}

相关问题