计算施加到物体上的力以减去生命值

时间:2019-06-08 11:09:32

标签: c# unity3d

我正在尝试从爆炸中计算施加到Player对象的力,并从施加的力中减去等于施加的力的生命值

我目前正在尝试使用OnCollisionEnter和collision.relativeVelocity,但是我无法将Vector 3转换为我用于HP的浮点数

//Class for player stats 
public static float HP =100f;

private void OnCollisionEnter(Collision collision)
{
    Vector3 velocity = collision.relativeVelocity;
    HP = HP - velocity;
}

//Explosion force code (separate class form player stats)
    Vector3 ExplosionPosition = Bomba.transform.position;
    Collider[] colliders = Physics.OverlapSphere(ExplosionPosition, 
    radius);
    foreach (Collider hit in colliders)
    {
        Rigidbody RB = hit.GetComponent<Rigidbody>();
        if (RB != null)
        {
            RB.AddExplosionForce(power, ExplosionPosition, radius, 
            upForce, ForceMode.Impulse);
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用代表矢量长度的幅度将Vector3转换为浮点数。

private void OnCollisionEnter(Collision collision)
{
    Vector3 velocity = collision.relativeVelocity;
    HP = HP - velocity.magnitude;
}

编辑:

根据评论,您可能需要自己进行计算:

 float distance = (objPosition - explosionPosition).magnitude;
 if (distance > explosionRange){ return 0.0f; } // Out of reach        
 return 1.0f - distance / explosionRange; 

这将使力线性下降。如果distance为0,则在爆炸中,您将得到1的全力。随着距离的增加,除法将接近1,值将接近0。