Esempio n. 1
0
    public override bool TestCollisionVsCircle(CircleCollisionHull2D other, ref Collision c)
    {
        c.a = this;
        c.b = other;
        // c.status
        // check if sqr distance between the center is less that the square of the radii
        updatePosition();
        other.updatePosition();
        // could use dot product
        float sqrDistance = (position - other.position).SqrMagnitude();
        float sqrRadii    = radius + other.radius;

        sqrRadii *= sqrRadii;

        bool isColiding = sqrDistance <= sqrRadii;

        if (!isColiding)
        {
            return(isColiding);
        }
        //contact point
        // http://paulbourke.net/geometry/circlesphere/
        Vector2 difference = other.position - position; //from position to other.position
        float   distance   = difference.magnitude;
        float   radii      = radius + other.radius;
        // distance = radii
        // Vector2 contact = position + difference;

        // Get point halfway between two centers.
        Vector2 contact = position + difference * (radius / (radius + other.radius)); //
        Vector2 normal  = (position - contact).normalized;                            // vector from contact to center
        float   overlap = radii - distance;                                           // not sure we need this.

        // edge cases - circles overlap completely, or one inside the other.

        c.contactCount            = 1;
        c.contacts                = new CollisionHull2D.Collision.Contact[c.contactCount];
        c.contacts[0].point       = contact;
        c.contacts[0].normal      = normal;
        c.contacts[0].restitution = restitution; // TODO: Is this coefficient or actual number?


        // closing velocity
        // https://gamedev.stackexchange.com/questions/118162/how-to-calculate-the-closing-speed-of-two-objects
        //Vector2 diff = other.position - position;
        //Vector2 velDiff = other.particle2D.getVelocity() - particle2D.getVelocity();
        //float closingSpeed = Vector2.Dot(velDiff, diff) / diff.magnitude;
        //Relative velocity from book
        Vector2 relativeVelocity = particle2D.getVelocity() - other.getParticle2D().getVelocity();
        float   separatingVel    = Vector2.Dot(relativeVelocity, normal); // relativeVelocity * normal

        // https://math.stackexchange.com/questions/13261/how-to-get-a-reflection-vector
        // this would simulate hitting a hard object w/ no velocity loss.
        // Vector2 velReflectedOverN = particle2D.getVelocity() - 2 * Vector2.Dot(particle2D.getVelocity(), normal) * normal;
        // c.closingVelocity =  closingSpeed*velReflectedOverN.normalized;
        c.closingVelocity = -separatingVel * normal; //was -seperatingVel
        c.status          = isColiding;
        return(isColiding);
    }