2D碰撞检查3个或更多对象之间

时间:2019-02-20 13:47:09

标签: c++ collision

我的碰撞检查算法有问题。 问题是当我尝试解决3个对象之间的冲突时,其中1个对象仍然没有碰撞并且无法解决冲突,这是代码:

void check_collisions(engine_t* engine)
{
    for (int i = 0; i < engine->actor_count; i++)
    {
        actor_t* first = (actor_t*)engine->collision_pairs->data[i];
        collider_t* a = (collider_t*)get_component_by_name(first, "collider");

        for(int j = 0; j < engine->actor_count; j++)
        {
            actor_t* second = (actor_t*)engine->collision_pairs->data[j];

            if(second == first)
                continue;

            collider_t* b = (collider_t*)get_component_by_name(second, "collider");

            hit_state_t hit = aabb(a, b);

            resolve_collisions(a, b, hit.normal);
        }
    }
}

问题是,例如:我有A,B,C

A可能在同一帧时间与B和C碰撞,似乎当更多物体碰撞时,第一个(第一个)物体将不再计算..知道吗?

void resolve_collisions(collider_t* a, collider_t* b, vec2_t normal)
{
    //Stop rigidbody
    vec2_t position = a->owner->transform.position;
    vec2_t position2 = b->owner->transform.position;
    rigid_body_t* rb = (rigid_body_t*)get_component_by_name(a->owner, "rigid_body");

    // if(!rb) { SDL_Log("rigid_body not while resolving collisions"); return; }

    //hit from dx
    if (normal.x > 0.0f && position.x < b->owner->transform.position.x + b->size.x)
    {
        rb->velocity.x = 0.0f;
        // SDL_Log("collided dx");
        position.x = (b->owner->transform.position.x + b->size.x) + 0.7f;
    }

    //hit from sx
    if (normal.x < 0.0f && position.x + a->size.x > b->owner->transform.position.x)
    {
        rb->velocity.x = 0.0f;

        float offset = b->size.x - a->size.x;
        float offset2 = a->size.x - b->size.x;
        // SDL_Log("collided sx");
        position.x = (b->owner->transform.position.x - b->size.x) + offset;
        position2.x = (a->owner->transform.position.x - a->size.x) + offset2;
    }

    //hit from top
    if (normal.y < 0.0f && position.y + a->size.y > b->owner->transform.position.y)
    {
        rb->velocity.y = 0.0f;
        float offset = b->size.y - a->size.y;
        position.y = (b->owner->transform.position.y - b->size.y) + offset;
    }

    //hit from bottom
    if (normal.y > 0.0f && position.y < b->owner->transform.position.y + b->size.y)
    {
        rb->velocity.y = 0.0f;
        // SDL_Log("collided bottom");
        position.y = (b->owner->transform.position.y + b->size.y) + 0.7f;
    }

    //change pos
    a->owner->transform.position = position;
}

任何帮助将不胜感激! -谢谢

0 个答案:

没有答案