示例#1
0
    private void ApplyForces()
    {
        Vector3 origin = transform.position;

        RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, explosionRadius, Vector2.up);
        foreach (RaycastHit2D hit in hits)
        {
            if (hit.rigidbody != null)
            {
                Vector2 distance           = (hit.transform.position - origin);
                float   normalizedDistance = Mathf.Clamp((explosionRadius - distance.magnitude) / explosionRadius, 0.1f, 1f);

                IForceAffected movementModel = hit.rigidbody.GetComponent <IForceAffected>();
                if (movementModel != null)
                {
                    float invNormDistSq = Mathf.Pow(normalizedDistance, 2);
                    movementModel.AddExternalForce(explosionForce * invNormDistSq * distance.normalized);
                }
                IDamageable damageable = hit.collider.GetComponent <IDamageable>();
                if (damageable != null)
                {
                    float damage = damageMinimum + damageDifference * normalizedDistance;
                    damageable.TakeDamage((int)damage, true);
                }
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(mouseKey))
        {
            Vector3 location = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            location.z = 0;

            RaycastHit2D[] hits = Physics2D.CircleCastAll(location, radius, Vector2.up);
            foreach (RaycastHit2D hit in hits)
            {
                if (hit.rigidbody != null)
                {
                    IForceAffected movementModel = hit.rigidbody.GetComponent <IForceAffected>();
                    if (movementModel != null)
                    {
                        Vector2 distance    = (hit.transform.position - location);
                        float   invNormDist = Mathf.Clamp((radius - distance.magnitude) / radius, 0.1f, 1f);
                        float   factor      = Mathf.Pow(invNormDist, 2);
                        Debug.Log("dist: " + distance);
                        Debug.Log("inv norm dist: " + invNormDist);
                        Debug.Log("Factor: " + factor);
                        Debug.Log("Force: " + force * factor * distance.normalized);
                        movementModel.AddExternalForce(force * factor * distance.normalized);
                    }
                }
            }
        }
    }